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

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

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

IT培訓(xùn)班

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

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

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

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

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

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

實現(xiàn)步驟

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

resources下創(chuàng)建一個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)完成。


分享到:

Java培訓(xùn)班課程javaee

Python培訓(xùn)機構(gòu)python大數(shù)據(jù)

web前端培訓(xùn)課程升級V8.5web

AI+設(shè)計培訓(xùn)課程ui

大數(shù)據(jù)培訓(xùn)課程cloud

軟件測試培訓(xùn)課程test

c

新媒體運營培訓(xùn)netmarket

產(chǎn)品經(jīng)理培訓(xùn)課程pm

linux培訓(xùn)Linux

movies

智能機器人培訓(xùn)robot

電商視覺設(shè)計課程uids

AI

集成電路應(yīng)用開發(fā)(嵌入式)培訓(xùn)課程jdbc

在線咨詢 我要報名
和我們在線交談!