Spring的jdbc模板2:使用开源的连接池
上篇简要介绍了如何在spring中配置默认的连接池和jdbc模板,这篇来介绍开源的连接池配置与属性引入
C3P0连接池配置:
引入jar包
配置c3p0连接池
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- ==============配置C3P0连接池=============== --> <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:3307/test"></property> <property name="user" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- ==============配置jdbc模板================ --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!-- ==属性注入== --> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
在实际开发中,习惯于将jdbc的这些配置抽取出来,使结构更加清晰,所以,接下来介绍引入属性文件
抽取属性文件
在src目录下新建jdbc.properties
修改applicationContext5.xml的代码为如下即可
<!-- ===============引入属性文件============= --> <!-- 第一种方式通过一个bean标签引入的(很少) --> <!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> --> <!-- 第二种方式,通过context标签引入 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- ==========配置c3p0连接池============ --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.url}"></property> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- ==============配置jdbc模板================ --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!-- ==属性注入== --> <property name="dataSource" ref="dataSource"></property> </bean>