目的
我们可以以数据库连接相关的参数为代表,把 Spring 配置⽂件中需要经常修改的字符串信息,转移到⼀个更⼩的配置⽂件中。更有利于维护、修改。
创建配置文件
在 resources 目录下创建 db.properties
配置文件。
jdbc.driveName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://**.**.*.*/learn?useSSL=false jdbc.username=root jdbc.password=*****
修改 Spring 配置文件
<?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:p="http://www.springframework.org/schema/p" 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="classpath:/db.properties"/> <bean id="conn" class="world.xuewei.inject.ConnectionFactoryBean"> <property name="driveName" value="${jdbc.driveName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>