第一步:修改applicationContext.xml文件的配置
<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 "> </beans>
作用:引入context命名空间和约束路径
第二步:在applicationContext.xml中加载properties配置文件
<context:property-placeholder location="classpath:jdbc.properties"/>
property-placeholder的意思大概就是引入位置
作用:将配置文件中的值存到Spring容器中
第三步:在applicationContext.xml中配置c3p0连接池bean对象
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 通过set方式在连接池对象中注入值 其中的${}为Spring表达式,用法和EL表达式相同作用是取出Spring容器中的值-->
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
第四步:开始测试
@Test
public void test() throws PropertyVetoException, SQLException, IOException {
// c创建ApplicationContext对象 然后由Spring帮我们创建ComboPooledDataSource对象 ApplicationContextapplicationContext=newClassPathXmlApplicationContext("applicationContext.xml");
ComboPooledDataSource ds =(ComboPooledDataSource)applicationContext.getBean("dataSource");
connection = ds.getConnection(); queryRunner = new QueryRunner(ds); System.out.println(connection);
}