Spring Boot学习笔记07--DataSource的创建方法

摘要

看完本文你将掌握如下知识点:

  1. Spring Boot项目中DataSource的创建方法

SpringBoot系列Spring Boot学习笔记


DataSource的创建方法

前面讲了很多Spring Boot数据访问方面的内容,在讲到自己扩展数据访问的时候,示例代码中给出的DataSource创建方式都是DriverManagerDataSource,比如:

1
2
3
4
5
#datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=newpwd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Value("${spring.datasource.driver-class-name}")
String driverClass;
@Value("${spring.datasource.url}")
String url;
@Value("${spring.datasource.username}")
String userName;
@Value("${spring.datasource.password}")
String passWord;

@Bean(name = "dataSource")
public DataSource dataSource() {

DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(passWord);
return dataSource;
}

如果有多个数据源,就再创建多个DriverManagerDataSource
一般生产项目中我们不会这样使用,通常可以使用org.apache.commons.dbcp.BasicDataSource


实际上Spring Boot为我们提供了简便的创建DataSource的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
#datasource
#需要执行数据源的类型
spring.datasource.ds1.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.ds1.url=jdbc:mysql://localhost:3306/springboot1?useUnicode=true&characterEncoding=utf-8
spring.datasource.ds1.username=root
spring.datasource.ds1.password=newpwd

spring.datasource.ds2.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.ds2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.ds2.url=jdbc:mysql://localhost:3306/springboot2?useUnicode=true&characterEncoding=utf-8
spring.datasource.ds2.username=root
spring.datasource.ds2.password=newpwd
1
2
3
4
5
6
7
8
9
10
11
12
@Bean(name = "dataSource1")
//application.properties中属性名称的前缀
@ConfigurationProperties(prefix = "spring.datasource.ds1")
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}

@Bean(name = "dataSource2")
@ConfigurationProperties(prefix = "spring.datasource.ds2")
public DataSource dataSource2() {
return DataSourceBuilder.create().build();
}

目前,此种方式支持如下几种数据源类型:

“org.apache.tomcat.jdbc.pool.DataSource”, “com.zaxxer.hikari.HikariDataSource”, “org.apache.commons.dbcp.BasicDataSource”, “org.apache.commons.dbcp2.BasicDataSource”

使用哪种数据源类型,就要在项目中加入相应的jar依赖,
比如org.apache.tomcat.jdbc.pool.DataSource

1
2
3
4
5
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
<version>8.5.6</version>
</dependency>