Spring的PropertyPlaceholderConfigurer应用

一、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这个属性文件的时候。根本就没有属性可以赋值了。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值