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其中一小部分用法,详细请查阅资料,这次记录只是记录我在项目中所遇到的问题,方便记忆,以防止自己以后再入坑,有纰漏请指出,不喜勿喷!


猜你喜欢

转载自blog.csdn.net/thinkingcao/article/details/80620240