项目中只会有一个context:property-placeholder 标签起作用

项目中只会有一个<context:property-placeholder/>起作用

参考:关于context:property-placeholder的一个有趣现象 - stamen的程序员之路 - ITeye博客
https://stamen.iteye.com/blog/1926166

项目中可以有多个 spring xml文件,但是
<context:property-placeholder location=“classpath*:conf/conf_a.properties”/>
语句只能有一个。
当多个spring xml文件中都有<context:property-placeholder /> 语句,项目启动过程中也只会加载一个,这时就看谁先谁后了, 先的保留,后的忽略!因此,只加载到了一个属性文件,因而造成无法正确进行属性替换的问题。

原因介绍:

(参考:关于<context:property-placeholder>的一个有趣现象 - stamen的程序员之路 - ITeye博客
https://stamen.iteye.com/blog/1926166)
到底出了啥问题

随便搜索了一下,还发现很多人遇到这个问题,这个就是来自stackoverflow的问题:
http://stackoverflow.com/questions/7940452/spring-application-context-not-able-to-load-property-placeholder-properties

可惜啊,好像都没有人给出正确的解决。

那究竟是什么问题呢?也想了很久哦…终于回想起来了(写书时读过Spring源码),原来是Spring容器采用反射扫描的发现机制,在探测到Spring容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描(Spring 3.1已经使用PropertySourcesPlaceholderConfigurer替代PropertyPlaceholderConfigurer了)。

而<context:property-placeholder/>这个基于命名空间的配置,其实内部就是创建一个PropertyPlaceholderConfigurer Bean而已。换句话说,即Spring容器仅允许最多定义一个PropertyPlaceholderConfigurer(或<context:property-placeholder/>),其余的会被Spring忽略掉(其实Spring如果提供一个警告就好了)。

拿上来的例子来说,如果A和B模块是单独运行的,由于Spring容器都只有一个PropertyPlaceholderConfigurer,因此属性文件会被正常加载并替换掉。如果A和B两模块集成后运行,Spring容器中就有两个PropertyPlaceholderConfigurer Bean了,这时就看谁先谁后了, 先的保留,后的忽略!因此,只加载到了一个属性文件,因而造成无法正确进行属性替换的问题。

多个配置文件的引入:

<context:property-placeholder location="/WEB-INF/classes/config_a.properties,
       /WEB-INF/classes/config_b.properties,
      /WEB-INF/classes/config_c.properties" />

猜你喜欢

转载自blog.csdn.net/weixin_43671497/article/details/88897769