春– $ \ {}は@Valueで機能していません
プロパティファイルを読み取るための単純なSpring@PropertySourceの例。
db.properties
db.driver=oracle.jdbc.driver.OracleDriver
AppConfig.java
@Configuration
@PropertySource("classpath:db.properties")
public class AppConfig {
@Value("${db.driver}")
private String driver;
ただし、プロパティプレースホルダー${}は@Valueで解決できません。driver変数を出力すると、「oracle.jdbc.driver」ではなく文字列${db.driver}が直接表示されます。 .OracleDriver」。
溶液
Spring@Valueの${}を解決するには、STATICPropertySourcesPlaceholderConfigurerBeanを手動で宣言する必要があります。 例えば :
AppConfig.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
@PropertySource("classpath:db.properties")
public class AppConfig {
@Value("${db.driver}")
private String driver;
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
XML構成の場合、SpringはPropertySourcesPlaceholderConfigurerを自動的に登録するのに役立ちます。
Note
この春のJIRAを読むSPR-8539
Note
このSpring @PropertySource exampleに興味があるかもしれません