6.Spring系列之Bean的配置3
阿新 • • 發佈:2018-04-06
enc 1.7 ole lex mysq get style 後置 分配
一、配置Bean的兩種方式之使用XML配置Bean
1.在IOC容器中引入外部屬性文件
在IOC容器中,當配置 Bean 時, 有時需要在 Bean 的配置裏引入系統部署的相關信息(例如:文件路徑、 數據源配置信息等).,而這些部署細節實際上需要和Bean配置相分離,Spring 提供了一個 PropertyPlaceholderConfigurer 的 BeanFactory 後置處理器,這個處理器允許Bean的部分配置轉移到屬性文件中,可以在IOC容器中使用形式為 ${var} 的變量,PropertyPlaceholderConfigurer 從屬性文件裏加載屬性, 並使用這些屬性來替換變量,Spring 還允許在屬性文件中使用 ${propName},以實現屬性之間的相互引用。
註意:隨著Spring的版本叠代,2.5之後的版本引入外部屬性文件有了簡化,可通過 <context:property-placeholder> 元素來引入外部屬性文件:
首先,我們引入c3p0和mysql驅動jar包:
c3p0-0.9.1.2.jar、mysql-connector-java-5.1.7-bin.jar
接著,創建db.properties配置文件,裏面配置著mysql連接信息:
jdbc.user=xxx jdbc.password=123456 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql://xxx:3306/spring
接著,在IOC容器中引入外部屬性文件以及配置數據庫連接信息:
<?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"/> <!-- 使用c3p0連接池,配置數據庫連接信息 --> <bean id="dataSource" 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> </beans>
最後,開始測試程序:
public class Main { @SuppressWarnings("resource") public static void main(String[] args) throws SQLException { ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 測試數據庫是否能連接 DataSource dataSource = (DataSource) ctx.getBean("dataSource"); System.out.println(dataSource.getConnection()); // 運行後輸出:com.mchange.v2.c3p0.impl.NewProxyConnection@376b4233 // 代表連接成功 } }
2..IOC容器中Bean的生命周期
6.Spring系列之Bean的配置3