天天看點

Spring-Bean配置-使用外部屬性檔案(轉)

Spring-Bean配置-使用外部屬性檔案

是以可以通過@value注解擷取配置檔案的key-value,生成一個配置檔案bean。用以在代碼中直接使用bean的方式。

•在配置檔案裡配置Bean時,有時需要在Bean的配置裡混入系統部署的細節資訊(例如:檔案路徑,資料源配置資訊等).而這些部署細節實際上需要和Bean配置相分離

•Spring 提供了一個PropertyPlaceholderConfigurer的BeanFactory後置處理器,這個處理器允許使用者将Bean配置的部分内容外移到屬性檔案中.可以在Bean配置檔案裡使用形式為${var} 的變量,PropertyPlaceholderConfigurer從屬性檔案裡加載屬性,并使用這些屬性來替換變量.

•Spring 還允許在屬性檔案中使用${propName},以實作屬性之間的互相引用。

案例:使用db.properties配置連接配接資料庫的資訊,通過bean配置檔案擷取該資訊,然後建立資料源;

db.properties配置資訊如下:

[plain] view plain copy

user=scott  

password=tiger  

dirverClass=oracle.jdbc.driver.OracleDriver  

jdbcUrl=jdbc\:oracle\:thin\:@localhost\:1521\:oracl  

beans配置檔案:applicationContext_properties.xml

[html] view plain copy

<?xml version="1.0" encoding="UTF-8"?>  

<beans xmlns="http://www.springframework.org/schema/beans"  

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

    xmlns:context="http://www.springframework.org/schema/context"  

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">  

    <!-- 導入屬性檔案 -->  

    <context:property-placeholder location="classpath:db.properties"/>  

    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">  

        <!-- 使用外部屬性檔案的屬性 -->  

        <property name="user" value="${user}"></property>  

        <property name="password" value="${password}"></property>  

        <property name="driverClass" value="${dirverClass}"></property>  

        <property name="jdbcUrl" value="${jdbcUrl}"></property>  

    </bean>  

</beans>  

建立資料源代碼如下:

[java] view plain copy

ApplicationContext axt = new ClassPathXmlApplicationContext("applicationContext_properties.xml");  

DataSource dataSource = (DataSource)axt.getBean("dataSource");  

System.out.println(dataSource.getConnection());