您的位置:首页 > 编程语言 > Java开发

Spring @Value 无法获取到properties文件中的值

2017-05-11 00:00 281 查看
摘要: 解析spring 中 @Value 获取值为null的错误

在非Controller层无法通过@Value获取值

变量不能使用 static 修改

spring mvc Controller中使用@Value无法获取属性值

在使用spring mvc时,实际上是两个spring容器:


dispatcher-servlet.xml 是一个,我们的controller就在这里,所以这个里面也需要注入属性文件
org.springframework.web.servlet.DispatcherServlet
这里最终是使用WebApplicationContext parent =WebApplicationContextUtils.getWebApplicationContext(getServletContext()); 创建spring容器,代码在FrameworkServlet中

applicationContext.xml 是另外一个,也需要注入属性文件
org.springframework.web.context.ContextLoaderListener
3.我们在的service中可以拿到@Value注入的值,那是因为我们通常都会把获取属性文件定义在applicationContext.xml(spring.xml)中,这样在 Controller中是取不到的,必须在dispatcher-servlet.xml 中把获取属性文件再定义一下

spring xml

spring.xml

spring-mvc.xml

spring-redis.xml

spring-mybatis.xml
因为系统启动时 spring-xml.xml 和 spring.xml,spring.xml-reids,spring-batis.xml 不是统一个容器,所以导致Controller无法通过@Value获取到(spring.xml,spring.xml-reids,spring-batis.xml)中关联的properties值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息