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

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

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

 

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

 

咋解决呢?url

通配符解决spa

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

_________________________________________________________________________________________blog

 spring 的properties解析 ip

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

通常使用PropertyPlaceholderConfigurer来替换占位符,例如:get

<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配合更好。

另外须要注意如下几点

一、在PropertyPlaceholderBeanDefinitionParser的父类中shouldGenerateId返回true,即默认会为每个bean生成一个惟一的名字; 若是使用了两个<context:property-placeholder则注册了两个PropertySourcesPlaceholderConfigurer Bean;因此不是覆盖(并且bean若是同名是后边的bean定义覆盖前边的); 二、PropertySourcesPlaceholderConfigurer本质是一个BeanFactoryPostProcessor,spring实施时若是发现这个bean实现了Ordered,则按照顺序执行;默认无序; 三、此时若是给<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'的 四、默认状况下ignore-unresolvable;即若是没找到的状况是否抛出异常。默认false:即抛出异常; <context:property-placeholder location="classpath*:conf/conf_a.properties" ignore-unresolvable="false"/>

相关文章
相关标签/搜索