- Spring中PropertyPlaceholderConfigurer的使用
-
可以通过Spring中的PropertyPlaceholderConfigurer来读取配置信息:
1. Properties[html]
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mysql
jdbc.username=root
jdbc.password=root
[html]
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath:jdbc.properties"/>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>Spring 2.5引进Context命名空间, 可以通过context:property-placeholder元素进行配置:
[html]
<context:property-placeholder location="classpath:jdbc.properties"/>PropertyPlaceholderConfigurer不仅可以根据指定的Properties文件来查找属性,也可以通过java系统属性模式。
spring 文档原文:
[html]
The PropertyPlaceholderConfigurer not only looks for properties in the Properties file you specify.
By default it also checks against the Java System properties if it cannot find a property in the specified properties files.
You can customize this behavior by setting the systemPropertiesMode property of the configurer with one of the following three supported integer values:
never (0): Never check system propertiesfallback (1): Check system properties if not resolvable in the specified properties files. This is the default.
override (2): Check system properties first, before trying the specified properties files. This allows system properties to override any other property source.
nerver(0): 不检查系统配置属性。
fallback(1): 检查系统配置属性,如果在指定属性文件中没有找到的话,使用系统配置属性,默认override(2): 首先检查系统配置属性,系统配置属性优先。
[html]
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/strategy.properties</value>
</property>
<property name="properties">
<value>custom.strategy.class=com.foo.DefaultStrategy</value>
</property>
</bean>
<bean id="serviceStrategy" class="${custom.strategy.class}"/>If the class cannot be resolved at runtime to a valid class, resolution of the bean fails when it is about to be created, which is during thepreInstantiateSingletons() phase of anApplicationContext for a non-lazy-init bean.
上面这段话的意思是,如果配置信息中使用了系统配置属性的方式,那么属性中的类在加载的时候就应该是非延迟加载的bean。
Spring 3.1 开始使用org.springframework.context.support.PropertySourcesPlaceholderConfigurer。
[html]
<!-- 方式一 -->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<!--方式二 -->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<!-- 方式三 -->
<context:property-placeholder location="classpath:jdbc.properties"/>