spring中 context:property-placeholder 导入多个独立的 .properties配置文件

spring中 context:property-placeholder 导入多个独立的 .properties配置文件?

Spring容器采用反射扫描的发现机制,在探测到Spring容器中有一个 org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的 Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描(Spring 3.1已经使用PropertySourcesPlaceholderConfigurer替代 PropertyPlaceholderConfigurer了)。

换句话说,即Spring容器仅允许最多定义一个PropertyPlaceholderConfigurer(或<context:property-placeholder/>),其余的会被Spring忽略掉(其实Spring如果提供一个警告就好了)。
拿上来的例子来说,如果A和B模块是单独运行的,由于Spring容器都只有一个PropertyPlaceholderConfigurer, 因此属性文件会被正常加载并替换掉。如果A和B两模块集成后运行,Spring容器中就有两个 PropertyPlaceholderConfigurer Bean了,这时就看谁先谁后了, 先的保留,后的忽略!因此,只加载到了一个属性文件,因而造成无法正确进行属性替换的问题。

咋解决呢?

通配符解决

<context:property-placeholder location="classpath*:conf/conf*.properties"/>  

_________________________________________________________________________________________

 spring 的properties解析 

来源: http://www.cnblogs.com/beiyeren/p/3488871.html

一般使用PropertyPlaceholderConfigurer来替换占位符,例如:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
      <value>classpath:com/foo/strategy.properties</value>
  </property>
  <property name="properties">
      <value>custom.strategy.class=com.foo.DefaultStrategy</value>
  </property>
</bean>

spring 2.5之后,可以使用

<context:property-placeholder location="classpath:com/foo/jdbc.properties"/>

其本质是注册了一个PropertyPlaceholderConfigurer(3.1之前)或者是PropertySourcesPlaceholderConfigurer(3.1之后)

Tip:


PropertyPlaceholderConfigurer内置的功能非常丰富,如果它未找到${xxx}中定义的xxx键,它还会去JVM系统属性(System.getProperty())和环境变量(System.getenv())中寻找。通过启用systemPropertiesMode和searchSystemEnvironment属性,开发者能够控制这一行为。

而PropertySourcesPlaceholderConfigurer在此基础上会和Environment and PropertySource配合更好。

另外需要注意以下几点

1、在PropertyPlaceholderBeanDefinitionParser的父类中shouldGenerateId返回true,即默认会为每一个bean生成一个唯一的名字; 如果使用了两个<context:property-placeholder则注册了两个PropertySourcesPlaceholderConfigurer Bean;所以不是覆盖(而且bean如果同名是后边的bean定义覆盖前边的); 
2、PropertySourcesPlaceholderConfigurer本质是一个BeanFactoryPostProcessor,spring实施时如果发现这个bean实现了Ordered,则按照顺序执行;默认无序; 
3、此时如果给<context:property-placeholder加order属性,则会反应出顺序,值越小优先级越高即越早执行; 
比如 
   <context:property-placeholder order="2" location="classpath*:conf/conf_a.properties"/>  
   <context:property-placeholder order="1" location="classpath*:conf/conf_b.properties"/> 
此时会先扫描order='1' 的,如果没有扫描order='2'的 
4、默认情况下ignore-unresolvable;即如果没找到的情况是否抛出异常。默认false:即抛出异常; 
<context:property-placeholder location="classpath*:conf/conf_a.properties" ignore-unresolvable="false"/>

原文地址:https://www.cnblogs.com/hfultrastrong/p/8427587.html