Spring3.0使用@Value碰到的一个状况

基于上一篇文章 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文件中的变量值成功
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值