更新時間:2023-05-11 來源:黑馬程序員 瀏覽量:
需求:將數據庫連接四要素提取到properties配置文件,spring來加載配置信息并使用這些信息來完成屬性注入。第三方bean屬性優(yōu)化的思路如下:
1.在resources下創(chuàng)建一個jdbc.properties(文件的名稱可以任意)
2.將數據庫連接四要素配置到配置文件中
3.在Spring的配置文件中加載properties文件
4.使用加載到的值實現屬性注入
其中第3,4步驟是需要重點關注,具體是如何實現。
實現步驟
步驟1:準備properties配置文件
resources下創(chuàng)建一個jdbc.properties文件,并添加對應的屬性鍵值對
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/spring_db
jdbc.username=root
jdbc.password=root
步驟2:開啟context命名空間
在applicationContext.xml中開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/springcontext.xsd">
</beans>
步驟3:加載properties配置文件
在配置文件中使用context命名空間下的標簽來加載properties配置文件
<context:property-placeholder location="jdbc.properties"/>
步驟4:完成屬性注入
使用${key}來讀取properties配置文件中的內容并完成屬性注入
<?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/springcontext.xsd">
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
</beans>
至此,讀取外部properties配置文件中的內容就已經完成。