LoginSignup
3
1

More than 5 years have passed since last update.

プロパティファイルからプレースホルダを用いてインジェクションするのに詰まった

Posted at

プロパティファイルから値を読み込んで、それを使うことって往々にしてあると思います。
自分もやってみるかって思って実装してみたんですけど、プレースホルダがうまく機能しなくて泣いてました。

プレースホルダ

xmlでconfig書いてると自動で有効化されるらしいですが、
Javaでconfig書いてると明示的に書いてあげないとだめらしいですね。

AppConfig
package jp.co.~~.~~.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@EnableAspectJAutoProxy
@PropertySource("classpath:application.properties")
// コントローラ配下以外をスキャン
@ComponentScan(basePackages = "jp.co.~~.~~", excludeFilters = @Filter(type = FilterType.REGEX, pattern = "^jp\\.co\\.~~\\.~~\\.web\\.controller.*$"))
public class AppConfig {

    /**
     * 
     * プレースホルダーの登録
     * これを明示的に書かないとプロパティのプレースホルダーが使えない
     * 
     * @return
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

これをbean定義しないと

こうなる
    @Value("${database.password}")
    String password;

    System.out.println(password); // ${database.password}って出力される
3
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1