很多時候,大多數Spring開發人員只是把整個部署的詳細資訊(資料庫的詳細資訊,日誌檔的路徑)寫在XML bean配置檔如下:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="customerDAO" class="com.zaixian.customer.dao.impl.JdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="customerSimpleDAO" class="com.zaixian.customer.dao.impl.SimpleJdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/zaixianjava" /> <property name="username" value="root" /> <property name="password" value="password" /> </bean> </beans>
但是,在企業環境中,部署的細節通常只可以由系統管理員或資料庫管理員來'觸碰',他們可能會拒絕直接訪問你的bean的配置檔,它們會要求部署配置一個單獨的檔,例如,一個簡單的性能(properties)檔,僅具有部署細節。
PropertyPlaceholderConfigurer示例
為了解決這個問題,可以使用 PropertyPlaceholderConfigurer 類通過一個特殊的格式在外部部署細節到一個屬性(properties )檔,以及訪問bean的配置檔 – ${variable}.
創建一個屬性檔(database.properties),包括資料庫的詳細資訊,把它放到你的專案類路徑。
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/zaixian_db jdbc.username=root jdbc.password=123456
在聲明bean配置檔和提供一個PropertyPlaceholderConfigurer映射到 剛才創建的“database.properties”屬性檔。
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>database.properties</value> </property> </bean>
完整的示例
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location"> <value>database.properties</value> </property> </bean> <bean id="customerDAO" class="com.zaixian.customer.dao.impl.JdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="customerSimpleDAO" class="com.zaixian.customer.dao.impl.SimpleJdbcCustomerDAO"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <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> </beans>
可替代用法
還可以使用 PropertyPlaceholderConfigurer 於某個常量,分享給所有其他bean。例如,定義在一個屬性檔中的日誌檔的位置,並通過 ${log.filepath} 訪問不同的 bean 配置檔的屬性值。