常见的数据源(链接池)有:DBCP、C3P0、Druid等等。
以C3P0数据源(C3P0连接池)为例,演示Spring对“非自定义对象”的配置。
Spring配置C3P0链接池的步骤:
1.导入数据源的坐标和数据库的驱动坐标
1 <!-- C3P0连接池 --> 2 <dependency> 3 <groupId>c3p0</groupId> 4 <artifactId>c3p0</artifactId> 5 <version>0.9.1.2</version> 6 </dependency> 7 8 <!-- mysql驱动 --> 9 <dependency> 10 <groupId>mysql</groupId> 11 <artifactId>mysql-connector-java</artifactId> 12 <version>5.1.39</version> 13 </dependency>
2.设置数据源的基本链接数据
分为手动创建C3P0链接池和使用Spring配置C3P0链接池:
使用Spring配置:在核心配置文件中配置如下:
1 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> 2 <property name="driverClass" value="com.mysql.jdbc.Driver"/> 3 <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/> 4 <property name="user" value="root"/> 5 <property name="password" value="root"/> 6 </bean>
优化配置为:将value后的值提取成一个新的配置文件jdbc.properties
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/test 3 jdbc.username=root 4 jdbc.password=root
然后修改核心配置文件中内容为:在核心配置文件中引入配置文件
<?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.xsd"> <!--引入classpath路径下的jdbc.properties文件--> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans>
手动:在测试类中编写运行,一般不采用此方法。
1 @Test 2 public void testC3P0() throws Exception { 3 //创建数据源 4 ComboPooledDataSource dataSource = new ComboPooledDataSource(); 5 //设置数据库连接参数 6 dataSource.setDriverClass("com.mysql.jdbc.Driver"); 7 dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); 8 dataSource.setUser("root"); 9 dataSource.setPassword("root"); 10 //获得连接对象 11 Connection connection = dataSource.getConnection(); 12 System.out.println(connection); 13 }
3.创建数据源对象,使用数据源获取连接资源和归还连接资源
在测试类中编写:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DataSource) applicationContext.getBean("dataSource"); Connection connection = dataSource.getConnection(); System.out.println(connection);
就可以实验是否成功创建数据源。