Spring 配置数据源
Spring 配置数据源
数据源(连接池)的作用
- 数据源(连接池)是提高程序性能而出现的
- 事先实例化数据源,初始化部分连接资源
- 使用连接资源时,从数据源中获取
- 使用完毕后将连接资源归还给数据源
常见的数据源(连接池):DBCP、C3P0、BoneCP、Druid等。
创建数据源步骤
- 导入数据库驱动坐标,数据源坐标
org.springframework
spring-context
5.0.5.RELEASE
junit
junit
4.12
mysql
mysql-connector-java
5.1.32
c3p0
c3p0
0.9.1.2
com.alibaba
druid
1.1.10
- 创建数据源对象
- 设置数据源属性
- 创建连接
- 使用连接
- 归还连接
手动创建 c3p0
在 junit 中测试连接情况,手动创建 c3p0
@Test
/*
* 手动创建c3p0数据源
* */
public void testDataSource() throws Exception {
// 创建数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
// 设置数据源属性
comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/****");
comboPooledDataSource.setUser("****");
comboPooledDataSource.setPassword("****");
// 创建连接
Connection connection = comboPooledDataSource.getConnection();
// 打印连接地址
System.out.println(connection);
// 将连接归还道数据源中
connection.close();
}
通过 properties 配置文件配置数据源
@Test
/*
* 手动创建c3p0数据源,加载配置文件形式
* */
public void testDataSourceWithProperties() throws Exception {
// 读取配置文件,ResourceBundle 是 java 提供的默认的资源读取包
// getBundle 的地址是相对于类路径加载地址,且不需要拓展名
ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
// 获取属性名
String driver = resourceBundle.getString("jdbc.driver");
String url = resourceBundle.getString("jdbc.url");
String username = resourceBundle.getString("jdbc.username");
String password = resourceBundle.getString("jdbc.password");
// 创建数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
// 设置数据源属性
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(username);
comboPooledDataSource.setPassword(password);
// 创建连接
Connection connection = comboPooledDataSource.getConnection();
// 打印连接地址
System.out.println(connection);
// 将连接归还道数据源中
connection.close();
}
Spring 配置数据源
可以将 DataSource 的创建权交由 Spring 容器去完成,并且在 applicationContext.xml 加载 jdbc.properties 配置文件获得连接信息。
xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
java 测试代码
@Test
/*
* 通过 Spring 创建c3p0数据源,加载配置文件形式
* */
public void testDataSourceWithSpring() throws Exception {
// 生成上下文对象
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
// 需要转换成 DataSource 类型,下面才能获取连接
DataSource dataSource = (DataSource) app.getBean("dataSource");
// 创建连接
Connection connection = dataSource.getConnection();
// 打印连接地址
System.out.println(connection);
// 将连接归还道数据源中
connection.close();
}
jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/****
jdbc.username=****
jdbc.password=****