本节也以一个小项目来做介绍,还是和HelloWorld的项目一样,不过多加了c3p0-0.9.1.2.jar和mysql-connector-java-5.1.34.jar的包。项目是以配置数据库的连接作为演示。项目中TestMain.java是测试类;db.properties是外部的属性文件(和spring配置文件一样放在src下);spring.xml是IOC容器配置文件。
详细的代码见下方不再做详细讨论,直接看外部文件和配置文件的关联。关键代码如下。
这里引入context命名空间,然后使用property-placeholder标签,location是外部属性文件的路径。这样设置完之后在dataSource的value中使用${ }将外部属性文件的key(key就是=左边的值)值填入其中即可完成外部属性文件的引入。
user=root
password=gzq123
drivenClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${drivenClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
</bean>
-------------------------------------------完整代码---------------------------------------------------------------------------------------------------------------------
TestMain.java
public class TestMain {
public static void main(String[] args) throws SQLException {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
DataSource ds = (DataSource) ctx.getBean("dataSource");
System.out.println(ds.getConnection());
}
}
db.properties
user=root
password=gzq123
drivenClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test
spring.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-4.1.xsd">
<!--
一、加载外部的属性文件
-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${drivenClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
</bean>
</beans>