一个简单的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
中@Value
,如果打印出driver
变量,它将直接显示字符串${db.driver}
,而不是“ oracle.jdbc.driver.OracleDriver”。
解
要在Spring @Value
解析${}
,您需要手动声明一个STATIC PropertySourcesPlaceholderConfigurer
bean。 例如 :
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
。
<util:properties location="classpath:db.properties"/>
注意
阅读此SpringJIRA SPR-8539
注意
您可能对此Spring @PropertySource示例感兴趣
翻译自: https://mkyong.com/spring/spring-is-not-working-in-value/