Spring的@Value无法加载相应的@PropertySource

一、问题详细:

        使用了@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>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一茗道人nview

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值