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