Spring beans使用参数占位符(JDBC配置读取示例)
beans.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" 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="db.properties"/> <!-- 占位符 得配置方式--> <bean id="dbUtil" class="com.my.util.DBUtil"> <property name="driverName" value="${driverName}"/> <property name="url" value="${url}"/> <property name="username" value="${username}" /> <property name="pwd" value="${pwd}"/> </bean> <!-- 注册propertyPlaceholderConfigurer对象-> <bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > <property name="locations"> <list> <value>db.properties</value> </list> </property> </bean> --> </beans>
db.properties 配置文件
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jg29
username=root
pwd=root
(# 降低耦合度,符合开闭原则【对拓展开、对修改源码闭】)