一、问题详细:
使用了@Value("${jdbc.driver}"),却无法获取jdbc.properties中的键值;仍然显示"${jdbc.driver}"字符串;
二、问题分析:
1、在Spring5.0版本前,要使用@Value,有两种方式:
①@PropertySource + Environment
②@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value
这里是由于没有创建PropertySourcesPlaceholderConfigurer方法,所以无法获取到对应值;
2、但在Spring5.0.5版本,可以不需要创建PropertySourcesPlaceholderConfigurer即可获取对应键值。
三、解决办法:
方法1、创建PropertySourcesPlaceholderConfigurer方法,例:
@Value("${jdbc.driver}")
private String driver;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
方法2、实例化Environment,例:
@Autowired
Environment environment;
public void dataSource() {
String driver = this.environment.getProperty("jdbc.driver");
System.out.println(driver);
}
方法3、升级Spring到5.0.5版本,pom.xml配置:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>