一、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这个属性文件的时候。根本就没有属性可以赋值了。
本文介绍Spring框架中PropertyPlaceholderConfigurer的使用方法,包括如何在XML配置文件中引用外部属性文件,以及处理多个属性文件之间的优先级问题。
814

被折叠的 条评论
为什么被折叠?



