# SpringBoot集成MySQL(整合Druid数据库连接池)教程

通过本教程从零开始,使用IDEA搭建名为SpringBoot-MySQL的企业级SpringBoot项目,整合MySQL 8.4.8数据库和Druid连接池,并基于JdbcTemplate实现数据库的增删改查操作,同时配置Druid监控功能。

# 1. 环境准备

在开始搭建项目前,请确保你的开发环境满足以下要求:

  • IDEA:2023及以上版本(推荐,兼容SpringBoot 3.x)
  • JDK:17及以上版本(SpringBoot 3.x系列强制要求JDK17+,低版本会启动失败)
  • MySQL:8.4.8(已安装并能正常访问,确保端口6033开放)
  • Maven:3.9.4(IDEA自带或手动安装均可)
  • SpringBoot:3.5.9
  • Druid:1.2.20(适配SpringBoot 3.x的稳定版本)

# 2. 使用IDEA创建SpringBoot项目

# 2.1 初始化项目

001

# 2.2 项目总体结构

项目默认结构如下:

SpringBoot-MySQL
    |   HELP.md
    |   mvnw
    |   mvnw.cmd
    |   pom.xml
    |
    \---src
        +---main
        |   +---java
        |   |   \---cc
        |   |       \---hep
        |   |           |   SpringBootMysqlApplication.java
        |   |           |
        |   |           +---common
        |   |           |       Result.java
        |   |           |
        |   |           +---config
        |   |           +---controller
        |   |           |       UserController.java
        |   |           |
        |   |           +---dao
        |   |           |       UserDao.java
        |   |           |
        |   |           +---entity
        |   |           |       User.java
        |   |           |
        |   |           +---exception
        |   |           |       BusinessException.java
        |   |           |
        |   |           \---service
        |   |               |   UserService.java
        |   |               |
        |   |               \---impl
        |   |                       UserServiceImpl.java
        |   |
        |   \---resources
        |       |   application.properties
        |       |   application.yml
        |       |
        |       +---static
        |       \---templates
        \---test
            \---java
                \---cc
                    \---hep
                        \---springbootmysql
                                SpringBootMySqlApplicationTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

# 3. 数据库环境准备

# 3.1 创建数据库

使用Navicat/MySQL Workbench/命令行连接MySQL,执行以下SQL创建指定数据库:

CREATE DATABASE IF NOT EXISTS hep_springboot_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE hep_springboot_db;
1
2

# 3.2 创建user表

创建user表用于后续功能验证,SQL如下:

CREATE TABLE IF NOT EXISTS `user` (
  `id` BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
  `username` VARCHAR(50) NOT NULL COMMENT '用户名',
  `password` VARCHAR(100) NOT NULL COMMENT '密码(实际项目需加密)',
  `age` INT DEFAULT 0 COMMENT '年龄',
  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
1
2
3
4
5
6
7

# 4. 引入核心依赖

替换pom.xml内容为以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.5.9</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<!-- 项目基本信息 -->
	<groupId>com.example</groupId>
	<artifactId>springboot-mysql</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBoot-MySQL</name>
	<description>SpringBoot集成MySQL+Druid的企业级项目</description>

	<properties>
		<java.version>17</java.version>
		<!-- Druid版本(适配SpringBoot3) -->
		<druid.version>1.2.20</druid.version>
	</properties>

	<dependencies>
		<!-- SpringWeb核心依赖(提供HTTP接口能力) -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- Spring JDBC核心依赖(提供JdbcTemplate操作数据库) -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

		<!-- MySQL驱动(适配MySQL8.4.8) -->
		<dependency>
			<groupId>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!-- Druid连接池SpringBoot Starter(简化Druid配置) -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-3-starter</artifactId>
			<version>${druid.version}</version>
		</dependency>

		<!-- SpringBoot测试依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.30</version>
			<scope>provided</scope>
		</dependency>


	</dependencies>

	<build>
		<plugins>
			<!-- SpringBoot打包插件 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

依赖说明:

  • spring-boot-starter-web:提供Web接口能力,用于编写Controller;
  • spring-boot-starter-jdbc:提供JdbcTemplate,简化数据库操作;
  • mysql-connector-j:MySQL8.x官方驱动(替代旧的mysql-connector-java);
  • druid-spring-boot-3-starter:Druid适配SpringBoot3的启动器,无需手动配置Druid核心Bean。

# 5. 配置数据库和Druid连接池

删除默认的application.properties,新建application.yml(企业级首选yml格式,更易读),配置内容如下:

# 服务器配置
server:
  port: 8080 # 项目启动端口

# Spring配置
spring:
  # 数据库连接配置
  datasource:
    # 使用Druid连接池
    type: com.alibaba.druid.pool.DruidDataSource
    # MySQL连接信息(使用你提供的数据库地址/账号/密码)
    url: jdbc:mysql://www.huerpu.cc:3306/hep_springboot_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    username: root
    password: root123
    # MySQL8.x驱动类(必须指定,否则可能加载旧驱动)
    driver-class-name: com.mysql.cj.jdbc.Driver

    # Druid连接池详细配置(企业级调优参数)
    druid:
      # 初始化连接数
      initial-size: 5
      # 最大活跃连接数
      max-active: 20
      # 最小空闲连接数
      min-idle: 5
      # 获取连接的最大等待时间(毫秒)
      max-wait: 60000
      # 检测空闲连接的时间间隔(毫秒)
      time-between-eviction-runs-millis: 60000
      # 连接的最小生存时间(毫秒)
      min-evictable-idle-time-millis: 300000
      # 验证连接是否有效(MySQL8.x推荐用SELECT 1)
      validation-query: SELECT 1 FROM DUAL
      # 申请连接时验证连接有效性
      test-on-borrow: false
      # 归还连接时验证连接有效性
      test-on-return: false
      # 空闲时验证连接有效性(推荐开启)
      test-while-idle: true
      # 开启PSCache(提升批量操作性能)
      pool-prepared-statements: true
      # PSCache最大缓存数
      max-pool-prepared-statement-per-connection-size: 20

      # Druid监控配置(企业级必备)
      stat-view-servlet:
        # 开启监控页面
        enabled: true
        # 监控页面访问路径
        url-pattern: /druid/*
        # 监控页面登录账号
        login-username: admin
        # 监控页面登录密码
        login-password: admin123
        # 是否允许重置监控数据
        reset-enable: false
      # Web应用监控(统计URL访问、Session等)
      web-stat-filter:
        enabled: true
        url-pattern: /*
        # 排除监控的路径
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
      # SQL监控(统计SQL执行耗时、次数等)
      filter:
        stat:
          enabled: true
          # 慢SQL阈值(毫秒),超过则记录日志
          slow-sql-millis: 5000
          # 记录慢SQL日志
          log-slow-sql: true
        # 防火墙(防止SQL注入,可选)
        wall:
          enabled: true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

配置说明:

  • spring.datasource.url:你的专属MySQL连接地址,包含时区、编码等关键参数;
  • druid.initial-size/max-active:连接池核心参数,根据业务场景调优;
  • druid.stat-view-servlet:Druid监控页面配置,访问http://localhost:8080/druid需登录;
  • druid.filter.stat:SQL监控配置,慢SQL阈值设为5秒,便于排查性能问题。

# 6. 搭建企业级项目目录结构

将基础结构扩展为企业级分层结构(解耦、易维护),目录如下:

SpringBoot-MySQL
├── src
│   ├── main
│   │   ├── java
│   │   │   └── cc.hep
│   │   │       ├── config(配置类,如Druid自定义配置)
│   │   │       ├── controller(控制层,接收HTTP请求)
│   │   │       ├── service(业务层接口)
│   │   │       │   └── impl(业务层实现)
│   │   │       ├── dao(数据访问层,操作数据库)
│   │   │       ├── entity(实体类,映射数据库表)
│   │   │       ├── common(公共类,如返回结果)
│   │   │       └── SpringBootMysqlApplication.java(启动类)
│   │   └── resources
│   │       └── application.yml(核心配置)
│   └── test(测试目录)
└── pom.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 7. 编写核心业务代码

# 7.1 实体类

映射user表的实体类,使用Lombok可简化代码(如需使用,需在pom.xml添加Lombok依赖),此处用基础写法:

package cc.hep.entity;

import java.time.LocalDateTime;

/**
 * 用户实体类(映射user表)
 */
public class User {
    // 主键ID
    private Long id;
    // 用户名
    private String username;
    // 密码
    private String password;
    // 年龄
    private Integer age;
    // 创建时间
    private LocalDateTime createTime;

    // 无参构造(JdbcTemplate查询需要)
    public User() {}

    // 有参构造(新增用户时使用)
    public User(String username, String password, Integer age) {
        this.username = username;
        this.password = password;
        this.age = age;
    }

    // Getter和Setter方法(必须,否则JdbcTemplate无法赋值)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public LocalDateTime getCreateTime() {
        return createTime;
    }

    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
    }

    // toString方法(便于打印日志/调试)
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", createTime=" + createTime +
                '}';
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

# 7.2 公共返回结果类

企业级项目统一返回格式,便于前端处理:

package cc.hep.common;

/**
 * 全局统一返回结果
 * @param <T> 数据类型
 */
public class Result<T> {
    // 响应码(200成功,500失败)
    private Integer code;
    // 响应消息
    private String msg;
    // 响应数据
    private T data;

    // 私有构造(通过静态方法创建)
    private Result() {}

    // 成功响应(带数据)
    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(200);
        result.setMsg("操作成功");
        result.setData(data);
        return result;
    }

    // 成功响应(无数据)
    public static <T> Result<T> success() {
        return success(null);
    }

    // 失败响应
    public static <T> Result<T> error(String msg) {
        Result<T> result = new Result<>();
        result.setCode(500);
        result.setMsg(msg);
        result.setData(null);
        return result;
    }

    // Getter和Setter
    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

# 7.3 数据访问层

基于JdbcTemplate实现数据库操作,企业级Dao层专注于数据CRUD:

package cc.hep.dao;

import cc.hep.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 用户数据访问层(操作user表)
 */
@Repository // 标识为数据访问组件,Spring自动扫描
public class UserDao {

    // 注入JdbcTemplate(SpringBoot自动配置,无需手动创建)
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 新增用户
     * @param user 用户对象
     * @return 受影响行数
     */
    public int addUser(User user) {
        String sql = "INSERT INTO user (username, password, age) VALUES (?, ?, ?)";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getAge());
    }

    /**
     * 根据ID查询用户
     * @param id 用户ID
     * @return 用户对象
     */
    public User getUserById(Long id) {
        String sql = "SELECT * FROM user WHERE id = ?";
        // BeanPropertyRowMapper:自动将查询结果映射为User实体
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
    }

    /**
     * 查询所有用户
     * @return 用户列表
     */
    public List<User> listAllUsers() {
        String sql = "SELECT * FROM user";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
    }

    /**
     * 更新用户信息
     * @param user 用户对象
     * @return 受影响行数
     */
    public int updateUser(User user) {
        String sql = "UPDATE user SET username = ?, password = ?, age = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getAge(), user.getId());
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return 受影响行数
     */
    public int deleteUser(Long id) {
        String sql = "DELETE FROM user WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

核心说明:

  • @Repository:标识该类为数据访问组件,Spring会自动扫描并创建Bean;
  • JdbcTemplate:Spring提供的数据库操作工具,自动处理连接获取/释放,避免手动管理Connection;
  • BeanPropertyRowMapper:自动将SQL查询结果映射为实体类(要求实体类属性名与数据库字段名一致)。

# 7.4 业务层接口

企业级项目通过接口定义业务能力,便于后续扩展(如多实现、AOP等):

package cc.hep.service;

import cc.hep.entity.User;

import java.util.List;

/**
 * 用户业务层接口
 */
public interface UserService {
    // 新增用户
    int addUser(User user);

    // 根据ID查询用户
    User getUserById(Long id);

    // 查询所有用户
    List<User> listAllUsers();

    // 更新用户
    int updateUser(User user);

    // 删除用户
    int deleteUser(Long id);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 7.5 业务层实现

实现业务接口,注入Dao层完成数据操作:

package cc.hep.service.impl;

import cc.hep.dao.UserDao;
import cc.hep.entity.User;
import cc.hep.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户业务层实现类
 */
@Service // 标识为业务组件,Spring自动扫描
public class UserServiceImpl implements UserService {

    // 注入Dao层
    @Autowired
    private UserDao userDao;

    @Override
    public int addUser(User user) {
        // 此处可添加业务逻辑(如密码加密、参数校验等)
        return userDao.addUser(user);
    }

    @Override
    public User getUserById(Long id) {
        return userDao.getUserById(id);
    }

    @Override
    public List<User> listAllUsers() {
        return userDao.listAllUsers();
    }

    @Override
    public int updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public int deleteUser(Long id) {
        return userDao.deleteUser(id);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46

说明:@Service标识该类为业务组件,Spring会自动创建Bean并注入到Controller层。

# 7.6 控制层

编写HTTP接口,接收前端请求,调用业务层处理:

package cc.hep.controller;

import cc.hep.common.Result;
import cc.hep.entity.User;
import cc.hep.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户控制层(提供HTTP接口)
 */
@RestController // 标识为REST接口,返回JSON数据
@RequestMapping("/user") // 接口统一前缀
public class UserController {

    // 注入业务层
    @Autowired
    private UserService userService;

    /**
     * 新增用户
     * POST /user/add
     * @param user 用户对象(JSON格式)
     * @return 响应结果
     */
    @PostMapping("/add")
    public Result<String> addUser(@RequestBody User user) {
        try {
            int rows = userService.addUser(user);
            if (rows > 0) {
                return Result.success("新增用户成功");
            } else {
                return Result.error("新增用户失败");
            }
        } catch (Exception e) {
            return Result.error("新增用户异常:" + e.getMessage());
        }
    }

    /**
     * 根据ID查询用户
     * GET /user/{id}
     * @param id 用户ID
     * @return 响应结果
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        try {
            User user = userService.getUserById(id);
            return Result.success(user);
        } catch (Exception e) {
            return Result.error("查询用户异常:" + e.getMessage());
        }
    }

    /**
     * 查询所有用户
     * GET /user/list
     * @return 响应结果
     */
    @GetMapping("/list")
    public Result<List<User>> listAllUsers() {
        try {
            List<User> userList = userService.listAllUsers();
            return Result.success(userList);
        } catch (Exception e) {
            return Result.error("查询用户列表异常:" + e.getMessage());
        }
    }

    /**
     * 更新用户
     * PUT /user/update
     * @param user 用户对象
     * @return 响应结果
     */
    @PutMapping("/update")
    public Result<String> updateUser(@RequestBody User user) {
        try {
            int rows = userService.updateUser(user);
            if (rows > 0) {
                return Result.success("更新用户成功");
            } else {
                return Result.error("更新用户失败");
            }
        } catch (Exception e) {
            return Result.error("更新用户异常:" + e.getMessage());
        }
    }

    /**
     * 删除用户
     * DELETE /user/delete/{id}
     * @param id 用户ID
     * @return 响应结果
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteUser(@PathVariable Long id) {
        try {
            int rows = userService.deleteUser(id);
            if (rows > 0) {
                return Result.success("删除用户成功");
            } else {
                return Result.error("删除用户失败");
            }
        } catch (Exception e) {
            return Result.error("删除用户异常:" + e.getMessage());
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112

核心说明:

  • @RestController:组合@Controller和@ResponseBody,返回JSON而非页面;
  • @RequestMapping("/user"):所有接口统一前缀,避免URL冲突;
  • @RequestBody:接收JSON格式的请求体;
  • @PathVariable:获取URL路径中的参数;
  • 异常捕获:企业级项目需捕获异常并返回友好提示,避免直接抛出系统异常。

# 7.7 主类SpringBootMysqlApplication

package cc.hep;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * SpringBoot-MySQL项目启动类
 * @SpringBootApplication 是核心注解,包含以下三个关键注解:
 * 1. @Configuration:标识该类为配置类,可定义Bean
 * 2. @EnableAutoConfiguration:开启自动配置(如自动配置JdbcTemplate、Druid数据源)
 * 3. @ComponentScan:扫描当前包及其子包下的@Component、@Service、@Repository、@Controller等注解的类
 */
@SpringBootApplication
public class SpringBootMysqlApplication {

	// 项目入口方法,main方法是Java程序的执行起点
	public static void main(String[] args) {
		// SpringApplication.run() 启动SpringBoot应用,加载上下文、初始化Bean、启动内置Tomcat
		SpringApplication.run(SpringBootMysqlApplication.class, args);
	}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 8. 测试验证

# 8.1 启动项目

运行SpringBootMysqlApplication.java的main方法,控制台无报错即启动成功:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.5.9)

2026-01-22T18:02:35.164+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] cc.hep.SpringBootMysqlApplication        : Starting SpringBootMysqlApplication using Java 17.0.12 with PID 25800 (C:\Users\Jason\IdeaProjects\SpringBoot\SpringBoot-MySQL\target\classes started by Jason in C:\Users\Jason\IdeaProjects\SpringBoot)
2026-01-22T18:02:35.167+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] cc.hep.SpringBootMysqlApplication        : No active profile set, falling back to 1 default profile: "default"
2026-01-22T18:02:35.989+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2026-01-22T18:02:36.000+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2026-01-22T18:02:36.000+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.50]
2026-01-22T18:02:36.034+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2026-01-22T18:02:36.035+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 828 ms
2026-01-22T18:02:36.105+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
2026-01-22T18:02:37.754+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2026-01-22T18:02:38.071+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2026-01-22T18:02:38.078+08:00  INFO 25800 --- [SpringBoot-MySQL] [           main] cc.hep.SpringBootMysqlApplication        : Started SpringBootMysqlApplication in 3.327 seconds (process running for 3.987)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 8.2 测试接口(Postman/Curl)

# 8.2.1 新增用户

  • 请求方式:POST
  • 请求URL:http://localhost:8080/user/add
  • 请求体(JSON):
{
  "username": "testUser",
  "password": "testPass123",
  "age": 25
}
1
2
3
4
5
  • 响应结果:
{
  "code": 200,
  "msg": "操作成功",
  "data": "新增用户成功"
}
1
2
3
4
5

# 8.2.2 查询所有用户

  • 请求方式:GET
  • 请求URL:http://localhost:8080/user/list
  • 响应结果:
{
  "code": 200,
  "msg": "操作成功",
  "data": [
    {
      "id": 1,
      "username": "testUser",
      "password": "testPass123",
      "age": 25,
      "createTime": "2026-01-22T10:01:00"
    }
  ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 8.3 访问Druid监控页面

  • 访问URL:http://localhost:8080/druid/index.html
  • 登录账号:admin,密码:admin123(application.yml中配置)
  • 核心监控模块:
    • 数据源:查看连接池状态(初始连接数、活跃连接数等);
    • SQL监控:查看执行的SQL语句、耗时、次数;
    • Web应用:查看接口访问次数、耗时;
    • 防火墙:查看SQL注入拦截记录(如有)。

# 总结

  1. SpringBoot3.5.9集成MySQL+Druid的核心是:引入mysql-connector-j、druid-spring-boot-3-starter、spring-boot-starter-jdbc依赖,配置application.yml中的数据源和Druid参数;
  2. 企业级项目需遵循分层架构(Controller > Service > Dao > Entity),解耦且易维护;
  3. Druid不仅是连接池,还提供监控、防火墙等功能,是企业级项目的首选;
  4. JdbcTemplate简化了数据库操作,无需手动管理连接,适合中小规模项目的数据库操作。

通过本教程,已搭建了一个完整的企业级SpringBoot-MySQL项目,包含数据库CRUD、统一返回格式、Druid监控等核心功能,可直接基于此扩展业务逻辑。

最近更新: 2026/2/3
 |  Copyright © -Present Kelsen All Rights Reserved. | Author KelsenJing