1. PropertyPlaceholderConfigurery使用
注解方式:
<context:property-placeholder location="classpath*:disconf.properties"
ignore-unresolvable="true"
ignore-resource-not-found="true" order = "2" />
bean方式:
<bean id="disconfStaticConfigPropertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!--找不到文件时不报错-->
<property name="ignoreResourceNotFound" value="true"/>
<!--是否应该忽略不可解析的占位符-->
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<!--order越小,越先被执行-->
<property name="order" value="1"/>
<!--本地配置文件-->
<property name="location" value="classpath*:disconf.properties" />
<property name="propertiesArray">
<list>
<!--Properties对象引用-->
<ref bean="disconfPropertiesReader"/>
</list>
</property>
</bean>
2. PropertyPlaceholderConfigurery原理
PropertyPlaceholderConfigurery继承关系
PropertyResourceConfigurer实现了BeanFactoryPostProcessor接口,在Spring读取了所有bean的配置元数据,但是还没有实例化的时候,完成读取配置文件,替换占位符。
1.mergeProperties
1.1 从本地配置读取
1.2 合并传递进来的properties
2.convertProperties
2.1替换properties中value中的占位符
3.processProperties
3.1 替换spring BeanDefinition中ParentName,BeanClassName,FactoryBeanName,FactoryMethodName,Scope,
PropertyValues,ConstructorArgumentValues中的占位符
3.2 替换spring Aliases别名中的占位符
3.3 addEmbeddedValueResolver添加到嵌入式值解析器列表中
3. 动态读取PropertyPlaceholderConfigurery
public class PropertyTest implements EmbeddedValueResolverAware {
private String tempFilePath;
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
//默认解析${}中的参数,
// 可以在定义PropertyPlaceholderConfigurery时设置placeholderPrefix,placeholderSuffix自定义分隔符
tempFilePath = resolver.resolveStringValue("${temp.file.path}");
}
}