基于上一篇文章 Spring3.0 对于@Configuration的使用 的后续 在使用Spring3.0使用@Value注入properties文件的变量时,出现值无法注入
原Spring3.0可在applicationContent.xml中使用
<context:property-placeholder location="classpath:spring/jdbc.properties" />
就可以将文件交给Spring来扫描,其中的值可以用@Value获取。
因为我是SpringBoot2.0代码重构到Spring3.0 使用@PropertySource(“classpath:param.properties”)指向读取变量文件,使用注解@Value发现值注入不到变量中
因我是基于注解开发的既没有
<context:property-placeholder ignore-unresolvable="true" location="classpath:redis-key.properties"/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis-key.properties</value>
</list>
</property>
</bean>
这两种配置我都没有导致没有将PropertyResourceConfigurer这个bean装载,Spring无法扫描到properties文件。
解决方法:创建一个类用@Configuration注解该类,并在该类下创建 PropertySourcesPlaceholderConfigurer的bean,将该bean装载到Spring容器中。
@Configuration
public class PropertyConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
启动项目输出properties文件中的变量值成功