Spring的PropertyPlaceholderConfigurer

来源:互联网 发布:淘宝申诉怎么写 编辑:程序博客网 时间:2024/05/05 01:02

使用PropertyPlaceholderConfigurer将系统相关变量分离懂到一个properties文件中,便于系统移植、切换。

<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /><property name="ignoreResourceNotFound" value="true" /><property name="locations"><list><!-- 标准配置 --><value>classpath*:/application.properties</value></list></property></bean>
 

官方注释:

A property resource configurer that resolves placeholders in bean property values of context definitions. It pulls values from a properties file into bean definitions.

The default placeholder syntax follows the Ant / Log4J / JSP EL style:

${...}
Example XML context definition:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">   <property name="driverClassName"><value>${driver}</value></property>   <property name="url"><value>jdbc:${dbname}</value></property> </bean>
Example properties file:
driver=com.mysql.jdbc.Driver dbname=mysql:mydb
PropertyPlaceholderConfigurer checks simple property values, lists, maps, props, and bean names in bean references. Furthermore, placeholder values can also cross-reference other placeholders, like:
rootPath=myrootdir subPath=${rootPath}/subdir
In contrast to PropertyOverrideConfigurer, this configurer allows to fill in explicit placeholders in context definitions. Therefore, the original definition cannot specify any default values for such bean properties, and the placeholder properties file is supposed to contain an entry for each defined placeholder.

If a configurer cannot resolve a placeholder, a BeanDefinitionStoreException will be thrown. If you want to check against multiple properties files, specify multiple resources via the "locations" setting. You can also define multiple PropertyPlaceholderConfigurers, each with its own placeholder syntax.

Default property values can be defined via "properties", to make overriding definitions in properties files optional. A configurer will also check against system properties (e.g. "user.dir") if it cannot resolve a placeholder with any of the specified properties. This can be customized via "systemPropertiesMode".

Note that the context definition is aware of being incomplete; this is immediately obvious to users when looking at the XML definition file. Hence, placeholders have to be resolved; any desired defaults have to be defined as placeholder values as well (for example in a default properties file).

Property values can be converted after reading them in, through overriding the PropertyResourceConfigurer.convertPropertyValue(java.lang.String) method. For example, encrypted values can be detected and decrypted accordingly before processing them.

 

参考:

http://thomaslee007.iteye.com/blog/167762