前言
今天在做框架改造时,碰到了不能@Value 不能获取属性的问题。纠结了好一阵,现做一个简单记录。
问题排查
- 将@Value("${key}") 直接替换成一个普通的常量试试
- 检查配置是否正确:
默认属性文件放在在resources
目录下,注入属性文件的方式有两种:
第一种:
<!-- 加载属性文件 -->
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1"/>
<!-- 忽略不能读取的属性 -->
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:redis.properties</value>
<value>classpath:global.properties</value>
</list>
</property>
</bean>
第二种
<context:property-placeholder location="classpath:*.properties" ignore-unresolvable="true"/>
- 检查属性文件有没有被加载到。
- 检查
@Value
的包是否引入错误,包名是:org.springframework.beans.factory.annotation.Value
我当时以上的情况都没有问题,属性文件加载到了,包名也没有弄错,但是属性就是注入不进来。百思不得其解,后来Google 才明白了。
进一步分析
我们都知道SSM 中有两个xml 文件配置,一个是Spring的配置,默认名是
applicationContext.xml, 放在WEB-INF下。一个是Spring-MVC的配置。默认名是[servlet-name]-servlet.xml ,放在WEB-INF 文件夹下。
在web.xml
中Spring的配置由ContextLoaderListener 加载,SpringMVC的相关配置由DispatcherServlet加载。
<!--加载spring的相关配置开始-->
<listener>
<description>springListerner</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!--加载spring的相关配置结束-->
<!--加载springMVC的相关配置开始-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--加载springMVC的相关配置结束-->
。。。。。。。。。。。。。。。。。
版权原因,完整文章,请参考如下:SSM框架@Value 不能获取属性分析