1、配置xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.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="${driverclass}"></property>
<property name="jdbcUrl" value="${jdbcurl}"></property>
</bean> </beans>
2、外部配置文件
user=root
password=admin
driverclass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql:///authority
3、main方法
package com.spring.properties; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.*;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
public static void main(String[] args) throws SQLException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-properties.xml"); DataSource dataSource = (DataSource)ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}