首頁技術(shù)文章正文

spring中怎樣優(yōu)化第三方bean?

更新時(shí)間:2023-05-11 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

需求:將數(shù)據(jù)庫連接四要素提取到properties配置文件,spring來加載配置信息并使用這些信息來完成屬性注入。第三方bean屬性優(yōu)化的思路如下:

1.在resources下創(chuàng)建一個(gè)jdbc.properties(文件的名稱可以任意)

2.將數(shù)據(jù)庫連接四要素配置到配置文件中

3.在Spring的配置文件中加載properties文件

4.使用加載到的值實(shí)現(xiàn)屬性注入

其中第3,4步驟是需要重點(diǎn)關(guān)注,具體是如何實(shí)現(xiàn)。

實(shí)現(xiàn)步驟

步驟1:準(zhǔn)備properties配置文件

resources下創(chuàng)建一個(gè)jdbc.properties文件,并添加對應(yīng)的屬性鍵值對

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命名空間下的標(biāo)簽來加載properties配置文件

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

步驟4:完成屬性注入

使用${key}來讀取properties配置文件中的內(nèi)容并完成屬性注入

<?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配置文件中的內(nèi)容就已經(jīng)完成。


分享到:
在線咨詢 我要報(bào)名
和我們在線交談!