本文纲要
SpringBoot整合JUnit
1.1 传统Spring整合JUnit回顾
1.2SpringBoot测试环境搭建
1.3 业务代码与测试类
1.4@SpringBootTest注解详解SpringBoot整合MyBatis
2.1 传统Spring整合MyBatis回顾
2.2 添加起步依赖
2.3 数据源与MyBatis配置
2.4Dao层开发与@Mapper注解
2.5 切换Druid连接池
2.6 版本差异与时区配置- 案例:基于
SpringBoot实现SSM整合
3.1 整合总览
3.2 项目结构与改造步骤
3.3 关键代码实现
3.3.1 依赖管理(pom.xml)
3.3.2 核心配置文件(application.yml)
3.3.3 数据层(Dao)
3.3.4 业务层(Service)
3.3.5 控制层(Controller)与统一返回对象
3.3.6 全局异常处理
3.3.7 静态资源与主页
3.4 测试运行 - 总结
SpringBoot 整合 JUnit
1 ) 传统 Spring 整合 JUnit 回顾
在传统 Spring 项目中编写单元测试,通常需要以下步骤:
- 使用
@RunWith(SpringJUnit4ClassRunner.class)指定 Spring 运行器 - 通过
@ContextConfiguration(classes/locations = ...)加载 Spring 配置类或配置文件 - 注入待测试对象
- 执行测试方法
尽管功能完整,但每个测试类都需要重复这些固定模板,代码冗余度高。
Spring Boot 对此进行了大幅简化。
2 ) 对比:传统整合 vs SpringBoot 整合
| 环节 | 传统 Spring 整合 | SpringBoot 整合 |
|---|---|---|
| 启动环境 | @RunWith(SpringRunner.class) | 无需手动指定(已内置) |
| 配置加载 | @ContextConfiguration 显式指定 | 自动加载引导类所在包下的 @SpringBootConfiguration |
| 测试类注解 | @SpringBootTest(可选,类上建议添加) | 使用 @SpringBootTest 声明为 Boot 测试 |
| 组件注入 | @Autowired + 配置扫描 | @Autowired 即可,引导类自动扫描同级及子包 |
| 测试方法 | 任意命名 | 任意命名(JUnit5) |
3 ) 整合步骤与代码实现
创建 SpringBoot 模块 springboot_07_test,依赖中已包含 spring-boot-starter-test(该依赖自动间接依赖 spring-boot-starter)。
项目结构
springboot_07_test
└── src
├── main
│ ├── java
│ │ └── com.wb
│ │ ├── Springboot07TestApplication.java # 引导类
│ │ └── service
│ │ ├── BookService.java # 接口
│ │ └── impl
│ │ └── BookServiceImpl.java # 实现类
│ └── resources
│ └── application.properties
└── test
└── java
└── com.wb1
└── Springboot07TestApplicationTests.java # 测试类
3.1 引导类
package com.wb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Springboot07TestApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot07TestApplication.class, args);
}
}
3.2 业务接口与实现
package com.wb.service;
public interface BookService {
void save();
}
package com.wb.service.impl;
import com.wb.service.BookService;
import org.springframework.stereotype.Service;
@Service
public class BookServiceImpl implements BookService {
@Override
public void save() {
System.out.println("book service is running ...");
}
}
3.3 测试类
测试类默认生成在 src/test/java 下,注解 @SpringBootTest 自动加载 Spring 环境。
若测试类与引导类不在相同包或其子包中,需通过 classes 属性显式指定引导类。
package com.wb1; // 注意:此包与引导类所在包不同
import com.wb.Springboot07TestApplication;
import com.wb.service.BookService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(classes = Springboot07TestApplication.class) // 显式指定引导类
class Springboot07TestApplicationTests {
@Autowired
private BookService bookService;
@Test
public void save() {
bookService.save();
}
}
3.4 运行测试
执行 save() 方法,控制台输出:
book service is running ...
证明测试通过
4 ) @SpringBootTest 原理小结
@SpringBootTest是 Spring Boot 提供的测试专用注解,内置运行器,自动寻找主配置类(@SpringBootConfiguration,通常由@SpringBootApplication组合)。- 若测试类位于引导类的包或子包下,则无需配置
classes属性;否则需要显式指定引导类。 - 测试方法可使用 JUnit5 的全部特性,无需额外配置。
SpringBoot 整合 MyBatis
1 ) 传统 Spring 整合 MyBatis 回顾
在传统 Spring 项目中整合 MyBatis 需要大量配置:
- 在 Spring 配置文件中引入数据源、
SqlSessionFactoryBean、MapperScannerConfigurer等 Bean。 - 手动管理事务。
- 配置 JDBC 驱动、URL、用户名、密码等。
Spring Boot 将这些繁琐配置全部内嵌,仅保留必要的声明。
2 ) 添加起步依赖
创建模块 springboot08mybatis,勾选或手动添加以下依赖:
mybatis-spring-boot-starter:整合 MyBatis 与 Spring Boot 的核心依赖,内含 MyBatis、MyBatis-Spring、Spring JDBC 等。mysql-connector-java:MySQL 驱动。
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
3 ) 数据源与 MyBatis 配置
所有配置集中在 application.yml 中,无需 XML。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
spring.datasource.*是 Spring Boot 内置数据源自动配置的固定前缀。- URL、用户名、密码按实际环境填写。
serverTimezone=UTC用于解决高版本 MySQL 驱动的时区兼容问题(详见下面第6条)。
4 )Dao 层开发与 @Mapper 注解
定义实体类 Book 和 Dao 接口,使用 @Mapper 标记接口,MyBatis 将自动为其生成代理实现类。
package com.wb.domain;
public class Book {
private Integer id;
private String name;
private String type;
private String description;
// getters & setters & toString 省略...
}
package com.wb.dao;
import com.wb.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
Book getById(Integer id);
}
测试类:
package com.wb;
import com.wb.dao.BookDao;
import com.wb.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
运行测试,控制台输出查询到的图书对象,整合成功。
5 ) 切换 Druid 连接池
Spring Boot 默认使用 HikariCP 连接池,若需要切换至 Druid,只需:
- 添加 Druid 依赖
- 在
application.yml中指定type
pom.xml 新增依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
修改 application.yml:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
重启测试,连接池生效。
6 ) 版本差异与时区问题
- Spring Boot 2.4.2 及更早版本 + MySQL 8.0 驱动可能因时区报错:
The server time zone value ...- 解决方案:在 URL 中添加
serverTimezone=UTC - 从 2.4.3 版本开始,驱动会自动协商时区,该参数可省略。
- MySQL 驱动类名变化:
- 新版驱动推荐使用
com.mysql.cj.jdbc.Driver,控制台会有相应提示,建议按提示修改。
- 新版驱动推荐使用
案例:基于 SpringBoot 实现 SSM 整合
1 ) 整合总览
将传统 SSM(Spring + SpringMVC + MyBatis)项目迁移到 Spring Boot,核心操作如下:
相较于传统 Spring 配置,SpringBoot 大幅减少了配置类数量,仅需保留少量代码。
对比传统整合与 SpringBoot 整合的改动项:
| 整合组件 | 传统 Spring | SpringBoot |
|---|---|---|
| Spring 容器 | 需配置 applicationContext.xml 或配置类 | 引导类代替,自动扫描 |
| SpringMVC | 需 spring-mvc.xml、DispatcherServlet 配置 | spring-boot-starter-web 自动配置 |
| MyBatis | SqlSessionFactoryBean、MapperScannerConfigurer 等 | 起步依赖 + @Mapper |
| 数据源 | 手动创建 DataSource Bean | application.yml 中配置 |
| 静态资源 | 放在 webapp 目录 | 放在 static 目录 |
| 异常处理 | 自定义 HandlerExceptionResolver | @RestControllerAdvice |
2 ) 项目结构与改造步骤
项目模块:springboot_09_ssm,最终目录结构如下:
springboot_09_ssm
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── com.wb
│ │ ├── Springboot09SsmApplication.java # 引导类
│ │ ├── controller
│ │ │ ├── BookController.java # REST 控制器
│ │ │ ├── Code.java # 业务状态码
│ │ │ ├── ProjectExceptionAdvice.java # 全局异常处理
│ │ │ └── Result.java # 统一返回对象
│ │ ├── dao
│ │ │ └── BookDao.java # 数据层接口(@Mapper)
│ │ ├── domain
│ │ │ └── Book.java # 实体类
│ │ ├── exception
│ │ │ ├── BusinessException.java
│ │ │ └── SystemException.java
│ │ └── service
│ │ ├── BookService.java # 业务接口
│ │ └── impl
│ │ └── BookServiceImpl.java # 业务实现
│ └── resources
│ ├── application.yml # 核心配置文件
│ └── static
│ ├── index.html # 主页跳转
│ └── pages
│ └── books.html # 图书列表页面
└── test
└── java
└── com.wb.service
└── BookServiceTest.java # 服务层单元测试
改造步骤:
- 导入原有代码到包
com.wb下。 - 删除
config目录(原 Spring 配置类全部移除)。 - 修改
pom.xml添加必要依赖。 - 将数据源配置迁移到
application.yml。 - 在
BookDao接口上添加@Mapper。 - 将原
webapp下的页面拷贝到resources/static。 - 配置主页跳转(可选)。
- 运行测试与 Web 服务。
3 ) 关键代码实现
3.1 依赖管理(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>2.5.0</version>
</parent>
<groupId>com.wb</groupId>
<artifactId>springboot09ssm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Web 起步依赖(含 SpringMVC) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis 整合起步依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- 额外添加 Druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2 核心配置文件(application.yml)
server:
port: 80 # 方便测试,直接使用80端口
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: root
所有数据源参数集中在 spring.datasource 下,Spring Boot 自动创建数据源并注入 MyBatis 环境。
3.3 数据层(Dao)
package com.wb.dao;
import com.wb.domain.Book;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper // 标志 MyBatis 映射接口,Spring 会自动扫描并创建代理
public interface BookDao {
@Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
int save(Book book);
@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
int update(Book book);
@Delete("delete from tbl_book where id = #{id}")
int delete(Integer id);
@Select("select * from tbl_book where id = #{id}")
Book getById(Integer id);
@Select("select * from tbl_book")
List<Book> getAll();
}
3.4 业务层(Service)
接口定义与事务声明:
package com.wb.service;
import com.wb.domain.Book;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional // 开启声明式事务
public interface BookService {
boolean save(Book book);
boolean update(Book book);
boolean delete(Integer id);
Book getById(Integer id);
List<Book> getAll();
}
实现类:
package com.wb.service.impl;
import com.wb.controller.Code;
import com.wb.dao.BookDao;
import com.wb.domain.Book;
import com.wb.exception.BusinessException;
import com.wb.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public boolean save(Book book) {
return bookDao.save(book) > 0;
}
public boolean update(Book book) {
return bookDao.update(book) > 0;
}
public boolean delete(Integer id) {
return bookDao.delete(id) > 0;
}
public Book getById(Integer id) {
if (id == 1) {
// 模拟业务异常
throw new BusinessException(Code.BUSINESS_ERR, "请不要使用你的技术挑战我的耐性!");
}
return bookDao.getById(id);
}
public List<Book> getAll() {
return bookDao.getAll();
}
}
3.5 控制层(Controller)与统一返回对象
统一返回对象 Result:
package com.wb.controller;
public class Result {
private Object data;
private Integer code;
private String msg;
public Result() {}
public Result(Integer code, Object data) {
this.code = code;
this.data = data;
}
public Result(Integer code, Object data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
}
// Getter & Setter 略...
}
状态码常量 Code:
package com.wb.controller;
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
public static final Integer SYSTEM_ERR = 50001;
public static final Integer SYSTEMTIMEOUTERR = 50002;
public static final Integer SYSTEMUNKNOWERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
REST 控制器 BookController:
package com.wb.controller;
import com.wb.domain.Book;
import com.wb.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVEOK : Code.SAVEERR, flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag ? Code.UPDATEOK : Code.UPDATEERR, flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag = bookService.delete(id);
return new Result(flag ? Code.DELETEOK : Code.DELETEERR, flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code = book != null ? Code.GETOK : Code.GETERR;
String msg = book != null ? "" : "数据查询失败,请重试!";
return new Result(code, book, msg);
}
@GetMapping
public Result getAll() {
List<Book> bookList = bookService.getAll();
Integer code = bookList != null ? Code.GETOK : Code.GETERR;
String msg = bookList != null ? "" : "数据查询失败,请重试!";
return new Result(code, bookList, msg);
}
}
3.6 全局异常处理
package com.wb.controller;
import com.wb.exception.BusinessException;
import com.wb.exception.SystemException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex) {
return new Result(ex.getCode(), null, ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex) {
return new Result(ex.getCode(), null, ex.getMessage());
}
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex) {
return new Result(Code.SYSTEMUNKNOWERR, null, "系统繁忙,请稍后再试!");
}
}
自定义异常类(略),统一通过上述 Advice 转换为规范的 JSON 返回。
3.7 静态资源与主页
Spring Boot 默认从 classpath:/static 目录提供静态资源。将原项目的 webapp 目录下的页面文件拷贝至 resources/static。
主页跳转文件 index.html:
<script>
document.location.href = "pages/books.html";
</script>
启动应用后,访问 http://localhost 即可自动跳转至图书管理页面。
4 ) 测试运行
单元测试类:
package com.wb.service;
import com.wb.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
@SpringBootTest
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById() {
Book book = bookService.getById(2); // 避开 id=1 的业务异常
System.out.println(book);
}
@Test
public void testGetAll() {
List<Book> all = bookService.getAll();
System.out.println(all);
}
}
直接运行测试方法,验证 Service 层功能。
启动 Web 服务:
运行引导类 Springboot09SsmApplication,浏览器访问 http://localhost,即可看到完整的图书增删改查界面,所有请求均通过 BookController 处理并返回 JSON 数据,前后端分离交互。
总结
通过以上三个模块的实践,可以清晰感受到 SpringBoot 在简化整合方面的巨大优势:
- JUnit 测试:一个
@SpringBootTest替代了运行器 + 配置类声明。 - MyBatis 整合:一个
mybatis-spring-boot-starter+@Mapper替代了多个 XML 配置。 - SSM 整合:引导类 + application.yml +
@Mapper+static目录,几乎零配置完成全栈整合。
这些特性的核心思想是 约定大于配置,让开发者专注于业务逻辑而非繁琐的环境搭建。
本篇入门覆盖了 SpringBoot 整合第三方框架的典型模式,后续可平滑扩展至其他技术栈(如 Redis、MQ 等)。SpringBoot 的出现,真正让 Java Web 开发变得轻快愉悦。
232



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



