首先导入jar包:
写需要引入的配置文件:
username=root
password=123
jdbcUrl=jdbc:mysql://localhost:3306/bjpowernode
driverClass=com.mysql.jdbc.Driver
让Spring帮我们创建连接对象,管理连接池,引用外部配置文件,依赖context名称空间
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
<property name="jdbcUrl" value="${jdbcUrl}"/>
<property name="driverClass" value="${driverClass}"/>
</bean>
测试类:
public class MyTest01 {
//根据spring的配置文件得到ioc容器对象
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
@Test
public void test1() throws SQLException {
//从容器拿连接池对象
ComboPooledDataSource dataSource = context.getBean("dataSource", ComboPooledDataSource.class);
System.out.println(dataSource.getConnection());
}
}