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

Spring的PropertyPlaceholderConfigurer应用

2016-06-07 22:35 453 查看
一、PropertyPlaceholderConfigurer作用

PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java Properties文件中去。

在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进行修改,而不用对xml配置文件进行修改。

二、使用方法

引入文件:

<bean id="properties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<list>
<value>classpath:a.properties</value>
</list>
</property>
</bean>
引入多个文件:

<bean id="properties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:a.properties</value>
<value>classpath:b.properties</value>
</list>
</property>
</bean>
PropertyPlaceholderConfigurer起的作用就是将占位符指向的配置信息放在bean中定义的工具:
<bean id="readpro" class="com.learn.spring.readpro">
<property name="name" value="${name}"/>
</bean>
java文件:
package com.learn.spring;

public class readpro {
public static String name;
public static String getName() {
return name;
}
public static void setName(String name) {
readpro.name = name;
}
}

三、使用注意
如果你需要两个配置文件,并且两个配置文件里都有name属性。

(1)如下配置以b.properties中属性值,即最后一个加载文件。

<bean id="properties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:a.properties</value>
<value>classpath:b.properties</value>
</list>
</property>
</bean>
(2)如下配置以a.properties中属性值为准,即第一个bean中的加载文件(该bean中多个文件且有相同属性名时,以最后一个含该属性名的属性值为准,与(1)相同)。
<bean id="properties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:a.properties</value>
</list>
</property>
</bean>
<bean id="propertie"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:b.properties</value>
</list>
</property>
</bean>


加载流程:

加载第一个PropertyPlaceholderConfigurer类的时候则扫描所有的bean然后把能赋值属性的都给赋值,当加载第二个PropertyPlaceholderConfigurer类属性配置文件的时候则再次扫描所有的bean然后把能赋值属性的都给赋值。所以这里我们先加载了第一个配置文件的时候就已经给name赋值了。当第二次加载b.properties这个属性文件的时候。根本就没有属性可以赋值了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PropertyPlaceholderC