目录
一、 两个文件
1. applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</beans>
2. jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
二、 将jdbc.properties文件加载到applicationContext.xml中,替换四个value
1.在beans标签属性中添加下边这段代码
xmlns:context="http://www.springframework.org/schema/context"
注:xmlns是XML Namespace的缩写,可译为“XML命名空间”
注:因为需要添加context:property-placeholder标签,而这个标签在http://www.springframework.org/schema/context命令空间中(即context命令空间),所以添加这行代码
2.在beans标签xsi:schemaLocation属性中添加新的位置
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
注:约束路径
3.加入标签context:property-placeholder
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
注:location=“jdbc.properties” 中 jdbc.properties为我们想要加载的properties文件全名
4.将4个value的key替换
<property name="driverClass" value="${jdbc.driverClassName}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
注:格式:value=“${key}”,key为jdbc.properties中的key
5.改完后的applicationContext.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">
<!--加载外部properties文件-->
<context:property-placeholder location="jdbc.properties"></context:property-placeholder>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClassName}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>
图文解析