【Spring 從0開始】IOC容器的Bean管理 - 基於XML - 外部屬性檔案
阿新 • • 發佈:2021-08-01
有時候,為了靈活方便,我們會把某些固定的資料存放到檔案裡,然後去讀取裡面的內容來使用。
比如資料庫的連線資訊,這些內容就可以放到 properties 檔案中,然後使用 xml 配置檔案去讀取裡面的內容,完成需要的注入。
這裡使用德魯伊連線池舉例,德魯伊連線池是阿里巴巴開源的資料庫連線池專案。
一、常規配置方法
1. 引入依賴
下載一個德魯伊的 jar 包,放到 lib 下面。
然後通過 File-Project Structure 新增這個 lib 下的jar包,應用。
2. xml 檔案配置資料庫連線池
<?xml version="1.0" encoding="UTF-8"?> <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.xsd"> <!--直接配置連線池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> </beans>
二、引入外部屬性檔案來配置資料庫連線池
1. 建立外部檔案
建立 properties 格式檔案,寫入資料庫資訊。
prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.username=root
prop.password=123456
2. 引入外部檔案到xml配置檔案中
把剛才建立的 properties 檔案引入到 spring 的配置檔案中來,通過使用名稱空間 context
。
<?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.xsd"> <!--引入外部屬性檔案--> <context:property-placeholder location="classpath:jdbc.properties"/> </beans>
3. 引用外部檔案裡的屬性
通過${}
--不要用肉體的勤奮,去掩蓋思考的懶惰--<?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.xsd"> <!--引入外部屬性檔案--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--配置連線池--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${prop.driverClass}"></property> <property name="url" value="${prop.url}"></property> <property name="username" value="${prop.username}"></property> <property name="password" value="${prop.password}"></property> </bean> </beans>