1:写在前面
该类的作用是替换配置文件中配置的占位符信息为properties文件中实际的值,原理是PropertyPlaceholderConfigurer实现了BeanFactoryPostProcessor接口,利用其在创建bean前能够修改BeanDefinition的特点,来替换修改占位符为properties文件中的实际值。另外,关于该类的源码分析可以参考这里。在spring中还一个类PropertyOverrideConfiguer,功能类似,感兴趣的朋友也可以看下。
2:例子
2.1:定义bean
public class MyPropertyPlaceholderConfigurerBean {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
}
2.2:xml和配置文件
- xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="propertyPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"
value="classpath:studyhelp/testpropertyplaceholderconfigurer.properties"/>
<property name="fileEncoding" value="UTF-8"/>
</bean>
<bean class="yudaosourcecode.studyhelp.MyPropertyPlaceholderConfigurerBean"
id="myPropertyPlaceholderConfigurerBean">
<property name="name" value="${my.name}"/>
<property name="age" value="${my.age}"/>
</bean>
</beans>
- 配置文件
my.name=张三的歌
my.age=900
- 测试
@Test
public void testpropertyplaceholderconfigurer() {
ClassPathXmlApplicationContext ac
= new ClassPathXmlApplicationContext("classpath*:studyhelp/testpropertyplaceholderconfigurer.xml");
System.out.println(ac.getBean("myPropertyPlaceholderConfigurerBean"));
}
- 运行
{"age":900,"name":"张三的歌"}
Process finished with exit code 0