SpringBoot
1 SpringBoot简介
SpringBoot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化 Spring 应用的初始搭建以及开发过程。
1.1 回顾SpringMVC
-
创建工程,并在
pom.xml
配置文件中配置所依赖的坐标 -
编写
web3.0
的配置类 -
编写
SpringMVC
的配置类 -
编写
Controller
类做到这只是将工程的架子搭起来。要想被外界访问,最起码还需要提供一个
Controller
类,在该类中提供一个方法。
从上面的 SpringMVC
程序开发可以看到,
前三步都是在搭建环境,而且这三步基本都是固定的。
**SpringBoot 就是对这三步进行简化了。**接下来我们通过一个入门案例来体现 SpingBoot 简化 Spring 开发。
1.2 SpringBoot快速入门
1.2.1 开发步骤
创建新模块
-
点击
+
选择New Module
创建新模块 -
选择
Spring Initializr
,用来创建SpringBoot
工程以前我们选择的是
Maven
,今天选择Spring Initializr
来快速构建SpringBoot
工程。而在Module SDK
这一项选择我们安装的JDK
版本。 -
对
SpringBoot
工程进行相关的设置我们使用这种方式构建的
SpringBoot
工程其实也是Maven
工程,而该方式只是一种快速构建的方式而已。注意:打包方式这里需要设置为
Jar
注意:基于Idea的
Spring Initializr
快速构建SpringBoot
工程时需要联网。 -
选中
Web
,然后勾选Spring Web
由于我们需要开发一个
web
程序,使用到了SpringMVC
技术,所以按照下图红框进行勾选
经过以上步骤后就创建了如下结构的模块,它会帮我们自动生成一个 Application
类,而该类一会再启动服务器时会用到

注意:
在创建好的工程中不需要创建配置类
创建好的项目会自动生成其他的一些文件,而这些文件目前对我们来说没有任何作用,所以可以将这些文件删除。
可以删除的目录和文件如下:
.mvn
.gitignore
HELP.md
mvnw
mvnw.cmd
删除完后的项目结构如下:
创建 Controller
在 com.example.controller
包下创建 BookController
,代码如下:
package com.example.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}
REST风格编程时,参数注解 @PathVariable 容易忘
启动服务器
运行 SpringBoot
工程不需要使用本地的 Tomcat
和 插件,只运行项目 com.example
包下的 Application
类,我们就可以在控制台看出如下信息
进行测试
使用 Postman
工具来测试我们的程序
报错解决
如果出现下面的报错:

解决方法:在Application类上添加相关包扫描的注解
最好的解决方法(不用加包的扫描注解):
运行类要直接放在example包里面:(不用加Scan扫描了)
运行分析
通过上面的入门案例我们可以看到使用 SpringBoot
进行开发,使整个开发变得很简单,那它是如何做到的呢?
@SpringBootApplication
@ComponentScan("com.example.xxx")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@SpringBootApplication
注解,而在主方法中就一行代码。我们在启动服务器时就是执行的该类中的主方法。
再看看 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.example</groupId>
<artifactId>springboot_01_quickstart</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!--JDK 的版本-->
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<!--该依赖就是我们在创建 SpringBoot 工程勾选的那个 Spring Web 产生的-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--这个是单元测试的依赖,我们现在没有进行单元测试,所以这个依赖现在可以没有-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!--这个插件是在打包时需要的,而这里暂时还没有用到-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
我们代码之所以能简化,就是因为指定的父工程和 Spring Web
依赖实现的。
1.2.2 与Spring对比
做完 SpringBoot
的入门案例后,接下来对比一下 Spring
程序和 SpringBoot
程序。如下图

-
坐标
Spring
程序中的坐标需要自己编写,而且坐标非常多SpringBoot
程序中的坐标是我们在创建工程时进行勾选自动生成的 -
web3.0配置类
Spring
程序需要自己编写这个配置类。这个配置类大家之前编写过,肯定感觉很复杂SpringBoot
程序不需要我们自己书写 -
配置类
Spring/SpringMVC
程序的配置类需要自己书写。而SpringBoot
程序则不需要书写。
1.2.3 官网构建工程
上面的实现中, Idea
使用了官网提供了快速构建 SpringBoot
工程的组件实现的。
进入SpringBoot官网
官网网址:https://spring.io/projects/spring-boot
如下:
进入到 SpringBoot
官网后拖到最下方就可以看到如下内容:
然后点击 Spring Initializr
超链接就会跳转到如下页面;
这和我们使用 Idea
快速构建 SpringBoot
工程的界面基本相同。在上面页面输入对应的信息
选择依赖
生成工程
解压后引入
以后即使没有 Idea
也可以使用官网的方式构建 SpringBoot
工程。
1.2.4 SpringBoot工程快速启动
1.2.4.1 问题导入

以后我们和前端开发人员协同开发,而前端开发人员需要测试前端程序就需要后端开启服务器,这就受制于后端开发人员。为了摆脱这个受制,前端开发人员尝试着在自己电脑上安装 Tomcat
和 Idea
,在自己电脑上启动后端程序,这显然不现实。
我们后端可以将 SpringBoot
工程打成 jar
包,该 jar
包运行不依赖于 Tomcat
和 Idea
这些工具也可以正常运行,只是这个 jar
包在运行过程中连接和我们自己程序相同的 Mysql
数据库即可。这样就可以解决这个问题,如下图

那现在问题是如何打包呢?
1.2.4.2 打包
由于我们在构建 SpringBoot
工程时已经在 pom.xml
中配置了如下插件
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
所以我们只需要使用 Maven
的 package
指令打包就会在 target
目录下生成对应的 Jar
包。
注意:该插件必须配置,不然打好的
jar
包也是有问题的。
1.2.4.3 启动
进入 jar
包所在位置,在 命令提示符
中输入如下命令
java -jar quick_start_02-0.0.1-SNAPSHOT.jar
执行上述命令就可以看到 SpringBoot
运行的日志信息

后端已启动,测试:
1.3 SpringBoot概述
原始 Spring
环境搭建和开发存在以下问题:
- 配置繁琐
- 依赖设置繁琐
SpringBoot
程序优点恰巧就是针对 Spring
的缺点
- **自动配置。**这个是用来解决
Spring
程序配置繁琐的问题 - **起步依赖。**这个是用来解决
Spring
程序依赖设置繁琐的问题 - 辅助功能(内置服务器,…)。我们在启动
SpringBoot
程序时既没有使用本地的tomcat
也没有使用tomcat
插件,而是**使用SpringBoot
内置的服务器**。
接下来我们来说一下 SpringBoot
的起步依赖
1.2.1 起步依赖
我们使用 Spring Initializr
方式创建的 Maven
工程的的 pom.xml
配置文件中自动生成了很多包含 starter
的依赖,如下图

这些依赖就是启步依赖。
1.2.1.1 探索父工程
从上面的文件中可以看到指定了一个父工程,我们进入到父工程,发现父工程中又指定了一个父工程,如下图所示

再进入到该父工程中,在该工程中我们可以看到配置内容结构如下图所示

上图中的 properties
标签中定义了各个技术软件依赖的版本,避免了我们在使用不同软件技术时考虑版本的兼容问题。在 properties
中我们找 servlet
和 mysql
的版本如下图

dependencyManagement
标签是进行依赖版本锁定,但是并没有导入对应的依赖;如果我们工程需要那个依赖只需要引入依赖的 groupid
和 artifactId
不需要定义 version
。
而 build
标签中也对插件的**版本进行了锁定**,如下图

看完了父工程中 pom.xml
的配置后不难理解**我们工程的的依赖为什么都没有配置 version
。**
那没有version,它是如何确定version的呢?
在Spring Boot中,版本的管理是通过使用所谓的"Dependency Management Plugin"来实现的。这个插件简化了依赖版本的管理,使得你可以在
pom.xml
中指定依赖,而不必显式指定版本号。如果你想查看Spring Boot当前版本及其所管理的依赖版本,可以查看Spring Boot官方网站上查看
那如果不想使用官方的版本号要怎么办呢?
可以在你的项目中显式指定每个依赖项的版本号。这样做时,你需要自行负责确保这些依赖项版本的兼容性。
1.2.1.2 探索依赖
在我们创建的工程中的 pom.xml
中配置了如下依赖

进入到该依赖,查看 pom.xml
的依赖会发现它引入了如下的依赖

里面的引入了 spring-web
和 spring-webmvc
的依赖,这就是为什么我们的工程中没有依赖这两个包还能正常使用 springMVC
中的注解的原因。
而依赖 spring-boot-starter-tomcat
,从名字基本能确认内部依赖了 tomcat
,所以我们的工程才能正常启动。
结论:以后需要使用技术,只需要引入该技术对应的起步依赖即可
1.2.1.3 小结
starter
SpringBoot
中常见项目名称,定义了**当前项目使用的所有项目坐标**,以达到减少依赖配置的目的
parent
-
所有
SpringBoot
项目**要继承的项目**,定义了若干个坐标版本号(依赖管理,而非依赖),以达到减少依赖冲突的目的 -
spring-boot-starter-parent
(2.5.0)与spring-boot-starter-parent
(2.4.6)共计57处坐标版本不同
感觉starter和parent都是继承,有什么区别呢?
parent
关注于构建配置的继承;使得你的项目能够继承父项目中的**默认配置**,而无需显式指定很多配置信息,如Java版本、插件版本等。这有助于简化项目的pom.xml
文件。starter
关注于依赖项的管理;Starter是一组预定义的依赖项集合,每个starter都关注**特定的功能或领域**,例如Web开发、数据访问等。
实际开发
-
使用任意坐标时,仅书写GAV中的G和A,V由SpringBoot提供
G:groupid
A:artifactId
V:version
-
如发生坐标错误,再指定version(要小心版本冲突)
1.2.2 程序启动
创建的每一个 SpringBoot
程序时都包含一个类似于下面的类,我们将这个类称作引导类
@SpringBootApplication
public class Springboot01QuickstartApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot01QuickstartApplication.class, args);
}
}
注意:
-
SpringBoot
在创建项目时,采用jar的打包方式 -
SpringBoot
的引导类是项目的入口,运行main
方法就可以启动项目因为我们在
pom.xml
中配置了spring-boot-starter-web
依赖,而该依赖通过前面的学习知道它依赖tomcat
,所以运行main
方法就可以使用tomcat
启动咱们的工程。
1.2.3 切换web服务器
现在我们启动工程使用的是 tomcat
服务器,那能不能不使用 tomcat
而使用 jetty
服务器,jetty
在我们 maven
高级时讲 maven
私服使用的服务器。而要切换 web
服务器就需要将默认的 tomcat
服务器给排除掉,怎么排除呢?使用 exclusion
标签
不光要排除 tomcat
服务器,还要引入 jetty
服务器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
运行引导类,在日志信息中就可以看到使用的是 jetty
服务器
小结:
通过切换服务器,我们不难发现在使用 SpringBoot
换技术时只需要导入该技术的起步依赖即可。
2 配置文件
2.1 配置文件格式
我们现在启动服务器默认的端口号是 8080
,访问路径可以书写为
http://localhost:8080/books/1
在线上环境我们还是希望将端口号改为 80
,这样在访问的时候就可以不写端口号了,如下
http://localhost/books/1
而 SpringBoot
程序如何修改呢?SpringBoot
提供了多种属性配置方式
-
application.properties
server.port=80
-
application.yml
server: port: 81
-
application.yaml
server: port: 82
注意:
SpringBoot
程序的配置文件名必须是 application ,只是后缀名不同而已。
运行后能在控制台看见端口号,和Context Path
项目结构(project structure)中没有Spring
项目结构的Facets中只有Web没有Spring
1 添加框架支持
1 或者,选中项目,双击shift
仍然不成功,没能添加spring…(暂时没找到原因)
之后再次启动,突然又出现了…
在配合文件中如果没有提示,可以使用Customize Spring Boot
三种配合文件的优先级
三种配置文件的优先级是:
application.properties > application.yml > application.yaml
注意:
SpringBoot
核心配置文件名为application
SpringBoot
内置属性过多,且所有属性集中在一起修改,在使用时,通过提示键+关键字修改属性例如要设置日志的级别时,可以在配置文件中书写
logging
,就会提示出来。配置内容如下logging: level: root: info
2.2 yaml格式
properties
类型的配合文件之前学习过
**YAML(YAML Ain’t Markup Language),一种数据序列化格式。**这种格式的配置文件在近些年已经占有主导地位,那么这种配置文件和前期使用的配置文件是有一些优势的,我们先看之前使用的配置文件。
最开始我们使用的是 xml
,格式如下:
<enterprise>
<name>itcast</name>
<age>16</age>
<tel>4006184000</tel>
</enterprise>
而 properties
类型的配置文件如下
enterprise.name=itcast
enterprise.age=16
enterprise.tel=4006184000
yaml
类型的配置文件内容如下
enterprise:
name: itcast
age: 16
tel: 4006184000
优点:
-
容易阅读
yaml
类型的配置文件比xml
类型的配置文件更容易阅读,结构更加清晰 -
容易与脚本语言交互
-
以数据为核心,重数据轻格式
yaml
更注重数据,而xml
更注重格式
YAML 文件扩展名:
.yml
(主流).yaml
上面两种后缀名都可以,以后使用更多的还是 yml
的。
2.2.1 语法规则
-
大小写敏感
-
属性层级关系使用多行描述,每行结尾使用冒号结束
-
使用缩进表示层级关系,同层级**左侧对齐**,只允许使用空格(不允许使用Tab键)
空格的个数并不重要,只要保证同层级的左侧对齐即可。
-
属性值前面添加空格(属性名与属性值之间使用**冒号+空格作为分隔**)
-
# 表示注释
核心规则:数据前面要加空格与冒号隔开
数组数据在数据书写位置的下方使用减号作为数据开始符号,每行书写一个数据,减号与数据间空格分隔,例如
enterprise:
name: itcast
age: 16
tel: 4006184000
subject:
- Java
- 前端
- 大数据
2.3 yaml配置文件数据读取
2.3.1 环境准备
在 com.baidu.domain
包下创建一个名为 Enterprise
的实体类等会用来封装数据,内容如下
public class Enterprise {
private String name;
private int age;
private String tel;
private String[] subject;
//setter and getter
//toString
}
在 resources
下创建一个名为 application.yml
的配置文件,里面配置了不同的数据,内容如下
lesson: SpringBoot
server:
port: 80
enterprise:
name: itcast
age: 16
tel: 4006184000
subject:
- Java
- 前端
- 大数据
2.3.2 读取配置数据
2.3.2.1 使用 @Value注解
使用 @Value("表达式")
注解可以从配合文件中读取数据,注解中用于读取属性名引用方式是:${一级属性名.二级属性名……}
我们可以在 BookController
中使用 @Value
注解读取配合文件数据,如下
@RestController
@RequestMapping("/books")
public class BookController {
@Value("${lesson}")
private String lesson;
@Value("${server.port}")
private Integer port;
@Value("${enterprise.subject[0]}")
private String subject_00;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(lesson);
System.out.println(port);
System.out.println(subject_00);
return "hello , spring boot!";
}
}
2.3.2.2 Environment对象
上面方式读取到的数据特别零散,SpringBoot
还可以使用 @Autowired
注解注入 Environment
对象的方式读取数据。这种方式 SpringBoot
会将配置文件中所有的数据封装到 Environment
对象中,如果需要使用哪个数据只需要通过调用 Environment
对象的 getProperty(String name)
方法获取。具体代码如下:
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Environment env;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(env.getProperty("lesson"));
System.out.println(env.getProperty("enterprise.name"));
System.out.println(env.getProperty("enterprise.subject[0]"));
return "hello , spring boot!";
}
}
注意:这种方式,框架内容大量数据,而在开发中我们很少使用。
2.3.2.3 自定义对象
SpringBoot
还提供了将配置文件中的数据封装到我们自定义的实体类对象中的方式。(即自己的Environment)
-
将实体类
bean
的创建交给Spring
管理。在类上添加
@Component
注解 -
使用
@ConfigurationProperties
注解表示加载配置文件在该注解中也可以使用
prefix
属性指定只加载指定前缀的数据 -
在
BookController
中进行注入
Component和Bean的区别
@Component
注解是Spring框架的通用组件扫描机制的一部分。它用于将一个类标识为Spring容器管理的组件。如拦截器。
@Bean
注解用于在Java配置类中声明一个方法,该方法的返回值将作为一个Bean注册到Spring容器中。
具体代码如下:
Enterprise
实体类内容如下:
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private int age;
private String tel;
private String[] subject;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String[] getSubject() {
return subject;
}
public void setSubject(String[] subject) {
this.subject = subject;
}
@Override
public String toString() {
return "Enterprise{" +
"name='" + name + '\'' +
", age=" + age +
", tel='" + tel + '\'' +
", subject=" + Arrays.toString(subject) +
'}';
}
}
BookController
内容如下:
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Enterprise enterprise;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(enterprise.getName());
System.out.println(enterprise.getAge());
System.out.println(enterprise.getSubject());
System.out.println(enterprise.getTel());
System.out.println(enterprise.getSubject()[0]);
return "hello , spring boot!";
}
}
运行结果:
2.4 多环境配置
以后在工作中,对于开发环境、测试环境、生产环境的配置肯定都不相同;
比如我们开发阶段会在自己的电脑上安装 mysql
,连接自己电脑上的 mysql
即可,但是项目开发完毕后要上线就需要该配置,将环境的配置改为线上环境的。

来回的修改配置会很麻烦,而 SpringBoot
给开发者提供了多环境的快捷配置,需要切换环境时只需要改一个配置即可。不同类型的配置文件对于多环境开发的配置都不相同
2.4.1 yaml文件
在 application.yml
中使用 ---
来分割不同的配置,内容如下
#开发
spring:
profiles: dev #给开发环境起的名字
server:
port: 80
---
#生产
spring:
profiles: pro #给生产环境起的名字
server:
port: 81
---
#测试
spring:
profiles: test #给测试环境起的名字
server:
port: 82
---
上面配置中 spring.profiles
是用来给不同的配置起名字的。
设置启动时对应的环境:告知 SpringBoot
使用哪段配置
#设置启用的环境
spring:
profiles:
active: dev #表示使用的是开发环境的配置
综上所述,application.yml
配置文件内容如下
#设置启用的环境
spring:
profiles:
active: dev
---
#开发
spring:
profiles: dev
server:
port: 80
---
#生产
spring:
profiles: pro
server:
port: 81
---
#测试
spring:
profiles: test
server:
port: 82
---
注意:
在上面配置中给不同配置起名字的
spring.profiles
配置项已经过时。最新用来起名字的配置项是#开发 spring: config: activate: on-profile: dev
2.4.2 properties文件
properties
类型的配置文件配置多环境,需要定义多个不同的配置文件
-
application-dev.properties
是**开发环境**的配置文件。我们在该文件中配置端口号为80
server.port=80
-
application-test.properties
是**测试环境**的配置文件。我们在该文件中配置端口号为81
server.port=81
-
application-pro.properties
是**生产环境**的配置文件。我们在该文件中配置端口号为82
server.port=82
SpringBoot
只会默认加载名为 application.properties
的配置文件,
所以需要在该配置文件中设置启用哪个配置文件,配置如下:
spring.profiles.active = pro
2.4.3 命令行启动参数设置
使用 SpringBoot
开发的程序以后都是打成 jar
包,通过 java -jar xxx.jar
的方式启动服务的。
那么就存在一个问题,如何切换环境呢?因为配置文件打到的jar包中了。
java –jar xxx.jar –-spring.profiles.active=test
那么这种方式能不能临时修改端口号呢?也是可以的,可以通过如下方式
java –jar xxx.jar –-server.port=88
当然也可以同时设置多个配置,比如即指定启用哪个环境配置,又临时指定端口,如下
java –jar springboot.jar –-server.port=88 –-spring.profiles.active=test
大家进行测试后就会发现**命令行设置的端口号优先级高**(也就是使用的是命令行设置的端口号),配置的优先级其实 SpringBoot
官网已经进行了说明,参见 :
https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config
进入上面网站后会看到如下页面
如果使用了多种方式配合同一个配置项,优先级高的生效。
2.5 配置文件分类

有这样的场景,我们开发完毕后需要测试人员进行测试,由于测试环境和开发环境的很多配置都不相同,所以测试人员在运行我们的工程时需要临时修改很多配置,如下
java –jar springboot.jar –-spring.profiles.active=test --server.port=85 --server.servlet.context-path=/heima --server.tomcat.connection-timeout=-1 …… …… …… …… ……
为什么配置不同是依靠配置文件放置不同的位置来解决的?
这里并没有说解决了这个问题。
针对这种情况,SpringBoot
定义了配置文件不同的放置位置;而放在不同位置的优先级是不同的。
SpringBoot
中4级配置文件放置位置:
- 1级:classpath:application.yml
- 2级:classpath:config/application.yml
- 3级:file :application.yml
- 4级:file :config/application.yml
file即打包之后在jar包所在的位置,如果创建一个config文件夹并且在里面放置application.yml就属于第4级
说明:级别越高优先级越高
3 SpringBoot整合junit
3.1 回顾
回顾 Spring
整合 junit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private BookService bookService;
@Test
public void testSave(){
bookService.save();
}
}
使用 @RunWith
注解指定运行器,使用 @ContextConfiguration
注解来指定配置类或者配置文件。
3.2 SpringBoot整合junit
-
在测试类上添加
SpringBootTest
注解 -
使用
@Autowired
注入要测试的资源 -
定义测试方法进行测试
编写测试类
@SpringBootTest class Springboot07TestApplicationTests { @Autowired private BookService bookService; @Test public void save() { bookService.save(); } }
注意:这里的引导类所在包必须是测试类所在包及其子包。
例如:
- 引导类所在包是
com.baidu
- 测试类所在包是
com.baidu
如果不满足这个要求的话,就需要在使用
@SpringBootTest
注解时,使用classes
属性指定引导类的字节码对象。如@SpringBootTest(classes = Springboot07TestApplication.class)
- 引导类所在包是
4 SpringBoot整合mybatis
4.1 回顾
回顾Spring整合Mybatis
Spring
整合 Mybatis
需要定义很多配置类
-
SpringConfig
配置类-
导入
JdbcConfig
配置类 -
导入
MybatisConfig
配置类@Configuration @ComponentScan("com.baidu") @PropertySource("classpath:jdbc.properties") @Import({JdbcConfig.class,MyBatisConfig.class}) public class SpringConfig { }
-
-
JdbcConfig
配置类-
定义数据源(加载properties配置项:driver、url、username、password)
public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String userName; @Value("${jdbc.password}") private String password; @Bean public DataSource getDataSource(){ DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(userName); ds.setPassword(password); return ds; } }
-
-
MybatisConfig
配置类-
定义
SqlSessionFactoryBean
-
定义映射配置
@Bean public MapperScannerConfigurer getMapperScannerConfigurer(){ MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("com.baidu.dao"); return msc; } @Bean public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource){ SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean(); ssfb.setTypeAliasesPackage("com.baidu.domain"); ssfb.setDataSource(dataSource); return ssfb; }
-
4.2 SpringBoot整合mybatis
4.2.1 创建模块
- 创建新模块,选择
Spring Initializr
,并配置模块相关基础信息

-
选择当前模块需要使用的技术集(MyBatis、MySQL)
出现报错:
选择“取消”,然后通过maven的pom.xml导入
4.2.2 定义实体类
在 com.baidu.domain
包下定义实体类 Book
,内容如下
public class Book {
private Integer id;
private String name;
private String type;
private String description;
//setter and getter
//toString
}
4.2.3 定义dao接口
在 com.baidu.dao
包下定义 BookDao
接口,内容如下
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
4.2.4 定义测试类
在 test/java
下定义包 com.baidu
,在该包下测试类,内容如下
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
4.2.5 编写配置
我们代码中并没有指定连接哪儿个数据库,用户名是什么,密码是什么。所以这部分需要在 SpringBoot
的配置文件中进行配合。
在 application.yml
配置文件中配置如下内容
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_db
username: root
password: 1234
4.2.6 测试
运行测试方法,我们会看到如下错误信息
1 驱动类的错误
驱动 com.mysql.jdbc.Driver 已被废弃,不再建议使用了(并非不可使用),推荐使用新的 MySQL JDBC 驱动 com.mysql.cj.jdbc.Driver,新的驱动可借助 SPI 自动注册并不再需要手动加载驱动。
需要说明的是这个不是错误,而是一个警告信息。
2 bookDao的错误
原因:Mybatis不知道使用哪一个dao接口来访问数据,添加@Mapper注解
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
获取数据结果:
注意:
SpringBoot
版本低于2.4.3(不含),Mysql驱动版本大于8.0时,需要在url连接串中配置时区jdbc:mysql://localhost:3306/spring_db?serverTimezone=UTC
,或在MySQL数据库端配置时区解决此问题
4.2.7 使用Druid数据源
现在我们并没有指定数据源,SpringBoot
有默认的数据源,我们也可以指定使用 Druid
数据源,按照以下步骤实现
-
导入
Druid
依赖<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency>
-
在
application.yml
配置文件配置可以通过
spring.datasource.type
来配置使用什么数据源。配置文件内容可以改进为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