【spring boot】第6篇:spring boot 整合 jdbc 数据源

4次阅读

共计 1342 个字符,预计需要花费 4 分钟才能阅读完成。

简述
以 jdbc 的形式访问 mysql 数据库是比较基础的知识,理解 spring boot 中如何使用 jdbc 对我们理解 spring boot 对 mybatis 等数据框架是很有意义的。
spring boot 整合 jdbc 的步骤
引入 starts 启动器
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
配置 application.yaml 文件
配置数据库相关信息
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/sff_test
driver-class-name: com.mysql.jdbc.Driver
这些配置信息都封装在 org.springframework.boot.autoconfigure.jdbc.DataSourceProperties 类中
运行测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootJdbcApplicationTests {
@Autowired
private DataSource dataSource;
@Test
public void testDataSource() throws SQLException {

System.out.println(“dataSource 类型:” + dataSource.getClass());

Connection connection = dataSource.getConnection();
System.out.println(“connection 连接:” + connection);
connection.close();
}
}
运行结果:从结果中可以看到 spring boot 的 2.1.2.RELEASE 版本默认使用 com.zaxxer.hikari.HikariDataSource 作为数据源。
spring boot 数据源自动配置原理
spring boot 对 jdbc 的自动配置类都封装在 org.springframework.boot.autoconfigure.jdbc 包下。
DataSourceConfiguration

该配置类中定义了 spring boot 支持的默认数据源种类

org.apache.tomcat.jdbc.pool.DataSource
com.zaxxer.hikari.HikariDataSource
org.apache.commons.dbcp2.BasicDataSource
通过 spring.datasource.type 属性指定自定义数据源类型,比如 druid、c3p0 等

正文完
 0