1.先回忆一下经典,还记得我们刚开始做web项目的时候,数据库连接的配置吗?
<context:property-placeholder location="classpath:db.properties"/>
这是一种加载.properties的方式,在xml的配置文件中直接可以通过${key}引用了
2.主角登场之前再介绍一种方式:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:quartz.properties</value>
</list>
</property>
</bean>
使用PropertiesFactoryBean和第一种是类似的,就是在取值的时候使用的是#{beanId['key']},今天不作为重点。
主角背景:
最近做了一个可配置属性的需求,对涉及到的PropertyPlaceholderConfigurer进行分析。
配置代码:
<bean id="diffsPlaceholderProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/spring/diff/diff.properties</value>
</list>
</property>
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="ignoreResourceNotFound" value="false" />
<property name="order" value="1" />
<property name="fileEncoding" value="utf-8" />
</bean>
先对配置快速过一下,locations属性可以配置属性文件的位置,systemPropertiesModeName属性是对系统属性的扫描规则。有如下三种方式
SYSTEM_PROPERTIES_MODE_FALLBACK
Check system properties if not resolvable in the specified properties.
检查系统配置文件如果给定的配置文件没有该属性。
SYSTEM_PROPERTIES_MODE_NEVER
Never check system properties.
从不检查系统属性。
SYSTEM_PROPERTIES_MODE_OVERRIDE
Check system properties first, before trying the specified properties.
在检查特定的配置文件之前先检查系统配置文件。
ignoreUnresolvablePlaceholders为true表示可以忽略未解析到的占位符,,如果不配,当多个配置文件出现在同一个xml中,会冲突,如下面这种,会出现冲突情况, ignoreUnresolvablePlaceholders为true就不会报错:
<bean id="propertyConfigurer1"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>
classpath:conf/test/test1.properties
</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer2"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>
classpath:conf/test/test2.properties
</value>
</list>
</property>
</bean>
ignoreResourceNotFound表示如果配置文件找不到是否忽略,默认为不忽略,这里其实是不用配的,默认就是false的。
order属性就是为了解决上面的冲突情况的,表示当发现冲突的时候以哪个PropertyPlaceholderConfigurer的配置为准,可以以int数字的形式设不同的优先等级
fileEncoding为编码格式
3. 我们将对以上的配置做个讲解,首先先看个类继承关系。
PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现。PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java Properties文件中去。
前面说的两种方式实际都是继承自PropertiesLoaderSupport的,可见它才是核心,它列出了配置文件的一些基本属性,PropertyResourceConfigurer继承自它,加了优先级order,PlaceholderConfigurerSupport又继承自PropertyResourceConfigurer,可以对使用的前缀后缀自定义(默认是${key}这样用),还可以配bean工厂,而PropertyPlaceholderConfigurer在PropertyResourceConfigurer的基础上对系统属性做了封装。
使用的时候直接用spring的@value注解,@Value注解可以用在属性上,也可以用在set方法上(但是光有属性,没有set方法是不是就无法赋值了,这个大家可以试一下)
使用方式如下:
@Value("${key}")
private String value;
这样就可以轻松使用PropertyPlaceholderConfigurer中配置的位置上的属性文件的键值了。
讲不好,后续再更新,有什么问题请各位看官提出来互相讨论,感恩。