1. 程式人生 > >使用外部屬性文件

使用外部屬性文件

prope beans hold 處理器 加載 contex 內容 屬性 文件

1.在配置文件裏配置Bean時,有時需要在Bean的配置裏混入系統部署的細節信息(如:文件路徑,數據源配置信息等)。而這些部署細節實際上需要和Bean配置相分離。

2.Spring提供了一個PropertyPlacehoiderConfigurer的BeanFactory後置處理器,這個處理器允許用戶將Bean配置的部分內容外移到屬性文件中。可以在Bean配置文件裏使用形式為${var}的變量,PropertyPlacehoiderConfigurer從屬性文件裏加載屬性,並使用這些屬性來替換變量。

3.Spring還允許在屬性文件中使用${propName},以實現屬性之間的相互引用。

如:

技術分享圖片

beans-properties.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> 7 8 <!-- 導入屬性文件 --> 9 <context:property-placeholder location="classpath:db.properties"/> 10 11 <bean id="dataSource" class="com.mysql.jdbc.Driver"
> 12 <!-- 使用外部化屬性文件的屬性 --> 13 <property name="user" value="${user}"></property> 14 <property name="password" value="${password}"></property> 15 <property name="driverClass" value="${driverClass}"></property> 16 <property name="jdbcUrl" value="${jdbcUrl}"></property> 17 </bean> 18 </beans>

註意:要導入context命名空間。

db.properties:

技術分享圖片

使用外部屬性文件