Spring注解@Value获取属性文件值且解决在controller无法获取到值的问题

一、说到@Value注解,用过的应该都知道,这是Spring3的一个注解,通过@value注解的方式获取properties文件中的配置值,大大简化了我们读取配置文件的代码

首先必须要配置properties文件的加载bean:在spring的配置文件中加入:让spring将properties的文件中的内容加载进spring容器中,将properties加入到Spring容器中有两种方式

1、以注入bean的形式
<bean id="appProperty"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <array>
            <value>classpath:weixin.properties</value>
        </array>
    </property>
</bean>
2、以下面这种形式,加载多个properties文件使用,隔开;
   <!-- 加载配置属性文件 -->
   <context:property-placeholder ignore-unresolvable="true"        location="classpath:jeesite.properties,classpath:weixin.properties" />
3、weixin.properties内容以键值对(key = value)形式存放

在这里插入图片描述

4、@Value使用

以 @Value("${key}")的形式获取properties中key对应的value值 , 以下为获取value值得代码

在这里插入图片描述

5、问题 :但是上述步骤还存在一个问题,就是我在Service中通过 @Value("${token}") 可以获取到token的值,但是在controller中无法获取到token的值,若要在Controller层也使用@Value访问properties配置的话,需要在xxx-servlet.xml(我这里是Spring-mvc.xml)中也定义properties配置文件。

解决 : 必须在Spring-mvc.xml中加入

    <!-- 加载配置属性文件 -->
    <context:property-placeholder ignore-unresolvable="true"        location="classpath:jeesite.properties,classpath:weixin.properties" />

在这里插入图片描述
总结 :

如上所示,同样的代码,写在在业务层,运行时能取到正确的值,但在控制层却取得了@Value注解中的Key(@Value注解有个特点,如果取不到值,那么不是返回一个null,而是返回Key)。

原因是controller注册在dispatcherservlet-servlet.xml代表的Spring MVC的容器中,而service则注册在application-context.xml代表的Spring的容器中。

如果context:property-placeholder只注册在Spring的容器中,那么自然只有业务层的类可以取到enable-upload-image的值,而控制器取不到值。

解决方法就是把各种context:property-placeholder在两个容器中都注册一下。如:

并且现在可以从属性文件读取,这只是@Value其中一小部分用法,详细请查阅资料,这次记录只是记录我在项目中所遇到的问题,方便记忆,以防止自己以后再入坑,有纰漏请指出,不喜勿喷!

作者:自由不过一种漂泊
原文:https://blog.csdn.net/Thinkingcao/article/details/80620240

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值