1. 程式人生 > >Spring Bean配置使用外部屬性檔案(十二)

Spring Bean配置使用外部屬性檔案(十二)

一、為什麼要在配置bean時使用外部屬性檔案?

   對於一般通用的配置,例如,連線資料庫配置資訊,會寫到properties檔案中,然後在XML配置檔案中呼叫相關的引數值。因而,我們需要將bean的屬性值從xml外部讀入到IOC容器中,這樣方便我們進行進行一些關鍵系統屬性資訊的修改。

二、bean配置資料庫連線資訊(不使用外部屬性檔案)

bean配置

<bean id="dbconfig" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="root"></property>
    <property name="password" value="mysql"></property>
    <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
</bean>

測試

public static void main(String[] args) throws SQLException {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    DataSource dataSource = (DataSource) applicationContext.getBean("dbconfig");
    System.out.println(dataSource.getConnection());
}

結果

三、不使用外部屬性檔案

在實際開發中,可能有很多配置,當我們需要進行修改時,需要在xml配置檔案中修改,很不方便。因而,我們可以將所有的配置資訊全部寫在屬性檔案中,直接載入配置就可以了,修改起來也非常方便。

(1)屬性檔案database.propertities

jdbc.user=root
jdbc.password=1230
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

(2)xml載入屬性檔案的值

(3)xml載入屬性檔案的值

  • 匯入名稱空間

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

http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
  • 匯入屬性檔案

<context:property-placeholder location="db.properties" />
  •  使用外部屬性檔案

<bean id="outerProperties" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="user" value="${jdbc.user}"></property>
    <property name="password" value="${jdbc.password}"></property>
    <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    <property name="driverClass" value="${jdbc.driverClass}"></property>
</bean>

測試

public static void main(String[] args) throws SQLException {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");

    DataSource dataSource = (DataSource) applicationContext.getBean("dbconfig");
    System.out.println(dataSource.getConnection());
}

結果