Spring之配置C3P0数据源
作用
数据源(连接池)的作用
- 提高程序性能
- 事先实例化数据源,初始化部分非连接资源
- 使用连接资源时从数据源中获取
- 使用完毕将连接资源归还给数据源
常见数据源
DBCP、C3P0、BoneCP、Druid
开发步骤
- 导入数据源的坐标和数据库驱动坐标
- 创建数据源对象
- 设计数据源的基本连接数据
- 使用数据源获取连接资源和归还连接资源
手动创建C3P0数据源
// 测试手动创建c3p0数据源
public void test1() throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
因为配置信息已经绑定到数据源里了,没有能更好的解耦合,所以可以将数据库的配置信息存放到jdbc.properties(配置文件名称随意)配置文件中,再读取配置文件中的配置信息来创建数据源。
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
// 测试手动创建c3p0数据源(加载配置文件形式)
// 目的:方便解耦,便于后期修改(编译之后配置文件不会改变,可以直接进行修改)
public void test3() throws Exception{
// 读取配置文件
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String driver = rb.getString("jdbc.driver");
String url = rb.getString("jdbc.url");
String username = rb.getString("jdbc.username");
String password = rb.getString("jdbc.password");
// 创建数据源对象
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
Spring配置数据源
为了使代码更加简化,可以将DataSource的创建权交由Spring 容器去完成
<beans xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/beans/spring-context.xsd">
在文件开头需要加入以上配置,然后使用context:property-placeholder标签读取properties文件,并通过Bean标签设置数据库信息。基本原理就是通过set方法注入。
<!-- 加载外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<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>
// 测试Spring容器产生c3p0数据源对象
public void test4() throws Exception{
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
// 如果只有一个DataSource类的注入,那么可以使用DataSource.class来替代Bean标签中的id。此处DataSource可以替代为任意注入类。
DataSource dataSource = app.getBean(DataSource.class);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}

浙公网安备 33010602011771号