星空网 > 软件开发 > Java

@Value取不到值引出的spring的2种配置文件applicationContext.xml和xxx

项目中经常会用到配置文件,定义成properties的形式比较常见,为了方便使用一般在spring配置文件中做如下配置:

<context:property-placeholder    ignore-unresolvable="true" location="classpath*:/application.properties" />

这样在程序代码中直接用@Value("${name}")就能直接取到properties文件中定义的变量值.

但是在一个项目中发现一个情况,在Controller中取不到这个值,直接输出了${name}字符串,并没有解析出值,而在service中却能取到.有点奇怪啊,明显在Controller中貌似并没有引入properties文件中的变量,而被当做普通的字符串处理了..突然想到这个项目有2个配置文件,1个在WEB-INF下的springmvc-servlet.

说实话之前并没有注意过这个配置文件的区别,一直以为只是放置的位置不一样而已,借助这次机会吧,查询到了一些资料.先看一则引入spring在web.

<!-- springmvc配置开始 -->
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 可以自定义servlet.--> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern></servlet-mapping>
<!-- springmvc配置结束 -->
<!-- Spring配置开始 --> 
<listener>
<listenerclass>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring Bean的配置文件所在目录。默认配置在WEB-INF目录下 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.</param-value>
</context-param>
<!-- Spring配置结束 -->

 可以看到分为spring配置和springmvc配置2种.其中spring配置以**的形式引入,不指定

值得注意的几点是:springmvc的配置文件中可以直接用id引入spring配置文件中定义的bean,但是反过来不可以.每一个springmvc的配置文件xxx-servlet.

百度中别人的帖子中看到一段应该是官方的原文解释,我摘抄过来并粗糙的直译一下:

Spring lets you define multiple contexts in a parent-child hierarchy.spring允许你定义多个上下文在父子继承关系中The applicationContext.applicationContext.The spring-servlet.spring-servlet.
one per Spring servlet (e.g. spring1-servlet.每一个spring的servlelt(例如: 名为spring1的servlet拥有配置文件spring1-servlet.Beans in spring-servlet.在spring-servlet.All Spring MVC controllers must go in the spring-servlet.所有springmvc的Controller必须在spring-servlet.In most simple cases, the applicationContext.在大多数简单的情况下, applicationContext.
in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.
如果你只有一个servlet, 那么实际没有什么必要定义applicationContext.

那么回到最开始的@Value取不到值的问题,现在的可以清楚由于Controller是定义在springmvc的servlet配置文件中的,所以在Controller中使用@Value注解会从springmvc的配置中查找,故只需要将placeholder重新在springmvc的配置中配置一遍,Controller中的@Value注解便能取到值了.




原标题:@Value取不到值引出的spring的2种配置文件applicationContext.xml和xxx

关键词:Spring

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流