Springboot 整合 druid
1. 创建Springboot项目
首先,需要创建 Springboot 项目(或 module):

添加 MyBatis Framework 和 mysql 依赖(dependencies):

2. 额外添加Druid依赖
Maven依赖网址快捷入口:Maven依赖网址
首先,搜索想要查找的依赖:

由于我们是 springboot 和 druid整合,所以选择第二个:

添加依赖:

这里贴上 1.2.6 版本的 druid 依赖:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
3. 配置druid
# 2. 配置相关信息
# 第一种配置方法:通过spring.datasource.type配置druid
#spring:
# datasource:
# driver-class-name: com.mysql.cj.jdbc.Driver # mysql 驱动
# url: jdbc:mysql://localhost:3306/springboot_test?characterEncoding=utf8&serverTimezone=UTC # 连接数据库
# username: root # 数据库账户
# password: root # 数据库密码
# type: com.alibaba.druid.pool.DruidDataSource
# 第二种配置方法:druid 专用配置(推荐)
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver # mysql 驱动
url: jdbc:mysql://localhost:3306/springboot_test?characterEncoding=utf8&serverTimezone=UTC # 连接数据库
username: root # 数据库账户
password: root # 数据库密码
4. 验证
创建 pojo实体类和 dao接口参考我的另一篇整合文章:
springboot 整合 mybatis
这里直接进行测试:
package com.example;
import com.example.dao.StudentDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Autowired
private StudentDao studentDao;
@Test
void contextLoads() {
System.out.println(studentDao.getStudentById("20000116"));
}
}

通过包名可知 Druid 已经生效。

本文详细介绍如何在SpringBoot项目中整合Druid数据库连接池,包括添加依赖、配置Druid参数及验证步骤。

1万+

被折叠的 条评论
为什么被折叠?



