1.有些參數在某些階段中是常量
比如:a、在開發階段我們連接數據庫時的連接url,username,password,driverClass等
b、分布式應用中client端訪問server端所用的server地址,port,service等
c、配置文件的位置
2.而這些參數在不同階段之間又往往需要改變
比如:在項目開發階段和交付階段數據庫的連接信息往往是不同的,分布式應用也是同樣的情況。
期望:能不能有一種解決方案可以方便我們在一個階段內不需要頻繁書寫一個參數的值,而在不同階段間又可以方便的切換參數配置信息
解決:spring3中提供了一種簡便的方式就是context:property-placeholder/元素
只需要在spring的配置文件里添加一句:<context:property-placeholder location="classpath:jdbc.properties"/> 即可,這里location值為參數配置文件的位置,參數配置文件通常放在src目錄下,而參數配置文件的格式跟java通用的參數配置文件相同,即鍵值對的形式,例如:
#jdbc配置
test.jdbc.driverClassName=com.mysql.jdbc.Driver
test.jdbc.url=jdbc:mysql://localhost:3306/test
test.jdbc.username=root
test.jdbc.password=root
行內#號后面部分為注釋
應用:
1.這樣一來就可以為spring配置的bean的屬性設置值了,比如spring有一個jdbc數據源的類DriverManagerDataSource
在配置文件里這么定義bean:
<bean
id="testDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="${test.jdbc.driverClassName}"/>
<property name="url" value="${test.jdbc.url}"/>
<property name="username" value="${test.jdbc.username}"/>
<property name="password" value="${test.jdbc.password}"/>
</bean>
---------------------------------------------------------
外在化應用參數的配置
在開發企業應用期間,或者在將企業應用部署到生產環境時,應用依賴的很多參數信息往往需要調整,比如LDAP連接、RDBMS JDBC連接信息。對這類信息進行外在化管理顯得格外重要。PropertyPlaceholderConfigurer和PropertyOverrideConfigurer對象,它們正是擔負著外在化配置應用參數的重任。
<context:property-placeholder/>元素
PropertyPlaceholderConfigurer實現了BeanFactoryPostProcessor接口,它能夠對<bean/>中的屬性值進行外在化管理。開發者可以提供單獨的屬性文件來管理相關屬性。比如,存在如下屬性文件,摘自userinfo.properties。
db.username=scott
db.password=tiger
如下內容摘自propertyplaceholderconfigurer.xml。正常情況下,在userInfo的定義中不會出現${db.username}、${db.password}等類似信息,這里采用PropertyPlaceholderConfigurer管理username和password屬性的取值。DI容器實例化userInfo前,PropertyPlaceholderConfigurer會修改userInfo的元數據信息(<bean/>定義),它會用userinfo.properties中db.username對應的scott值替換${db.username}、db.password對應的tiger值替換${db.password}。最終,DI容器在實例化userInfo時,UserInfo便會得到新的屬性值,而不是${db.username}、${db.password}等類似信息。
- <bean id="propertyPlaceholderConfigurer"
- class="org.springframework.beans.factory.config.
- PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>userinfo.properties</value>
- </list>
- </property>
- </bean>
- <bean name="userInfo" class="test.UserInfo">
- <property name="username" value="${db.username}"/>
- <property name="password" value="${db.password}"/>
- </bean>
通過運行并分析PropertyPlaceholderConfigurerDemo示例應用,開發者能夠深入理解PropertyPlaceholderConfigurer。為簡化PropertyPlaceholderConfigurer的使用,Spring提供了<context:property-placeholder/>元素。下面給出了配置示例,啟用它后,開發者便不用配置PropertyPlaceholderConfigurer對象了。
- <context:property-placeholder location="userinfo.properties"/>
PropertyPlaceholderConfigurer內置的功能非常豐富,如果它未找到${xxx}中定義的xxx鍵,它還會去JVM系統屬性(System.getProperty())和環境變量(System.getenv())中尋找。通過啟用systemPropertiesMode和searchSystemEnvironment屬性,開發者能夠控制這一行為。
文章列表