更新時(shí)間:2023-05-11 來源:黑馬程序員 瀏覽量:
IT就到黑馬程序員.gif)
需求:將數(shù)據(jù)庫(kù)連接四要素提取到properties配置文件,spring來加載配置信息并使用這些信息來完成屬性注入。第三方bean屬性優(yōu)化的思路如下:
1.在resources下創(chuàng)建一個(gè)jdbc.properties(文件的名稱可以任意)
2.將數(shù)據(jù)庫(kù)連接四要素配置到配置文件中
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文件,并添加對(duì)應(yīng)的屬性鍵值對(duì)
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)完成。
1024首播|39歲程序員逆襲記:不被年齡定義,AI浪潮里再迎春天
2025-10-241024程序員節(jié)丨10年同行,致敬用代碼改變世界的你
2025-10-24【AI設(shè)計(jì)】北京143期畢業(yè)僅36天,全員拿下高薪offer!黑馬AI設(shè)計(jì)連續(xù)6期100%高薪就業(yè)
2025-09-19【跨境電商運(yùn)營(yíng)】深圳跨境電商運(yùn)營(yíng)畢業(yè)22個(gè)工作日,就業(yè)率91%+,最高薪資達(dá)13500元
2025-09-19【AI運(yùn)維】鄭州運(yùn)維1期就業(yè)班,畢業(yè)14個(gè)工作日,班級(jí)93%同學(xué)已拿到Offer, 一線均薪資 1W+
2025-09-19【AI鴻蒙開發(fā)】上海校區(qū)AI鴻蒙開發(fā)4期5期,距離畢業(yè)21天,就業(yè)率91%,平均薪資14046元
2025-09-19