Spring Boot基础


Spring Boot是什么

官网:Spring Boot

众所周知 Spring 应用需要进行大量的配置,各种 XML 配置和注解配置让人眼花缭乱,且极容易出错,因此 Spring 一度被称为“配置地狱”。

为了简化 Spring 应用的搭建和开发过程,Pivotal 团队在 Spring 基础上提供了一套全新的开源的框架,它就是 Spring Boot。

Spring Boot 具有 Spring 一切优秀特性,Spring 能做的事,Spring Boot 都可以做,而且使用更加简单,功能更加丰富,性能更加稳定而健壮。随着近些年来微服务技术的流行,Spring Boot 也成为了时下炙手可热的技术。

Spring Boot 提供了大量开箱即用(out-of-the-box)的依赖模块,例如 spring-boot-starter-redis、spring-boot-starter-data-mongodb 和 spring-boot-starter-data-elasticsearch 等。这些依赖模块为 Spring Boot 应用提供了大量的自动配置,使得 Spring Boot 应用只需要非常少量的配置甚至零配置,便可以运行起来,让开发人员从 Spring 的“配置地狱”中解放出来,有更多的精力专注于业务逻辑的开发。

Spring Boot 的特点

Spring Boot 具有以下特点:

  1. 独立运行的 Spring 项目

Spring Boot 可以以 jar 包的形式独立运行,Spring Boot 项目只需通过命令“ java–jar xx.jar” 即可运行。

  1. 内嵌 Servlet 容器

Spring Boot 使用嵌入式的 Servlet 容器(例如 Tomcat、Jetty 或者 Undertow 等),应用无需打成 WAR 包 。

  1. 提供 starter 简化 Maven 配置

Spring Boot 提供了一系列的“starter”项目对象模型(POMS)来简化 Maven 配置。

  1. 提供了大量的自动配置

Spring Boot 提供了大量的默认自动配置,来简化项目的开发,开发人员也通过配置文件修改默认配置。

  1. 自带应用监控

Spring Boot 可以对正在运行的项目提供监控。

  1. 无代码生成和 xml 配置

Spring Boot 不需要任何 xml 配置即可实现 Spring 的所有配置。

IDEA创建Spring Boot项目

配置开发环境

在使用 Spring Boot 进行开发之前,第一件事就是配置好开发环境。这里我们以 Windows 操作系统为例,如果您使用的是其他操作系统,请对照其相关设置进行操作。

工欲善其事,必先利其器,IDE(集成开发环境)的选择相当重要,目前市面上有很多优秀的 IDE 开发工具,例如 IntelliJ IDEA、Spring Tools、Visual Studio Code 和 Eclipse 等等,那么我们该如何选择呢?

这里我们极力推荐大家使用 IntelliJ IDEA,因为相比于与其他 IDE,IntelliJ IDEA 对 Spring Boot 提供了更好的支持。

Spring Boot 版本及其环境配置要求如下表。

Spring Boot 2.x
JDK 8.0 及以上版本
Maven 3.x
IntelliJ IDEA 14.0 以上

创建 Spring Boot 项目

开发环境配置完成后,接下来,我们就可以通过 Intellij IDEA 创建一个 Spring Boot 项目了。

Intellij IDEA 一般可以通过两种方式创建 Spring Boot 项目:

  • 使用 Maven 创建
  • 使用 Spring Initializr 创建

使用 Maven 创建

  1. 使用 IntelliJ IDEA 创建一个名称为 helloworld 的 Maven 项目,创建过程请参考 IDEA 新建 Maven 项目

  2. 在该 Maven 项目的 pom.xml 中添加以下配置,导入 Spring Boot 相关的依赖。

<project>
    ...
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependencies>
        <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>
...
</project>
  1. 在 net.biancheng.www 包下,创建一个名为 helloWorldApplication 主程序,用来启动 Spring Boot 应用,代码如下。
package net.biancheng.www;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class helloWorldApplication {
    public static void main(String[] args) {
        SpringApplication.run(helloWorldApplication.class, args);
    }
}

Spring Boot 项目目录结构如下图。

使用 Spring Initializr 创建

IntelliJ IDEA 支持用户使用 Spring 项目创建向导(Spring Initializr )快速地创建一个 Spring Boot 项目,步骤如下。

  1. 在 IntelliJ IDEA 欢迎页面左侧选择 Project ,然后在右侧选择 New Project,如下图。

或者在 IntelliJ IDEA 工作区上方的菜单栏中选择 File ,在下拉菜单中选则 New,然后选择 Project,如下图。

  1. 在新建工程界面左侧,选择 Spring Initializr,选择项目的 SDK 为 1.8,选择 starter service URL 为 http://start.spring.io(默认),最后点击下方的 Next 按钮进行下一步。

  1. IDEA 会连接网络,并根据 starter service URL 查询 Spring Boot 的当前可用版本和组件列表,如下图。

  1. 在 Spring Initializr Project Settings 中,输入项目的 GroupId、ArtifactId 等内容,注意 Type 为 Maven,packaging 为 jar,Java version 切换为 8(默认为 11),最后点击下方的 Next 按钮,进行下一步。

  1. 在 dependencise 界面中,选择 Spring Boot 的版本及所依赖的 Spring Boot 组件(例如 Spring Boot 的版本为 2.4.5, Spring Boot 组件为 Web),然后点击下方的 Next 按钮。

  1. 根据需要修改项目名称及项目存储位置等信息,最后点击 Finish 按钮,完成 Spring Boot 项目的创建,如下图。

启动 Spring Boot

默认情况下,Spring Boot 项目会创建一个名为 ***Application 的主程序启动类 ,该类中使用了一个组合注解 @SpringBootApplication,用来开启 Spring Boot 的自动配置,另外该启动类中包含一个 main() 方法,用来启动该项目。

直接运行启动类 HelloworldApplication 中的 main() 方法,便可以启动该项目,结果如下图。

注意:Spring Boot 内部集成了 Tomcat,不需要人为手动配置 Tomcat,开发者只需要关注具体的业务逻辑即可。

为了能比较的清楚的看到效果,我们在 net.biancheng.www 包下又创建一个 controller 包,并在该包内创建一个名为 HelloController 的 Controller,代码如下。

package net.biancheng.www.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
        return "Hello World!";
    }
}

重启 Spring Boot 项目,然后在地址栏访问 “http://localhost:8080/hello”,结果如下图。

Spring Boot starter入门

传统的 Spring 项目想要运行,不仅需要导入各种依赖,还要对各种 XML 配置文件进行配置,十分繁琐,但 Spring Boot 项目在创建完成后,即使不编写任何代码,不进行任何配置也能够直接运行,这都要归功于 Spring Boot 的 starter 机制。

starter

Spring Boot 将日常企业应用研发中的各种场景都抽取出来,做成一个个的 starter(启动器),starter 中整合了该场景下各种可能用到的依赖,用户只需要在 Maven 中引入 starter 依赖,SpringBoot 就能自动扫描到要加载的信息并启动相应的默认配置。starter 提供了大量的自动配置,让用户摆脱了处理各种依赖和配置的困扰。所有这些 starter 都遵循着约定成俗的默认配置,并允许用户调整这些配置,即遵循“约定大于配置”的原则。

并不是所有的 starter 都是由 Spring Boot 官方提供的,也有部分 starter 是第三方技术厂商提供的,例如 druid-spring-boot-starter 和 mybatis-spring-boot-starter 等等。当然也存在个别第三方技术,Spring Boot 官方没提供 starter,第三方技术厂商也没有提供 starter。

以 spring-boot-starter-web 为例,它能够为提供 Web 开发场景所需要的几乎所有依赖,因此在使用 Spring Boot 开发 Web 项目时,只需要引入该 Starter 即可,而不需要额外导入 Web 服务器和其他的 Web 依赖。

在 pom.xml 中引入 spring-boot-starter-web,示例代码如下。

<?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>
    <!--SpringBoot父项目依赖管理-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/>
    </parent>
    ....
    <dependencies>
        <!--导入 spring-boot-starter-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        ...
    </dependencies>
    ...
</project>

在该项目中执行以下 mvn 命令查看器依赖树。

mvn dependency:tree

执行结果如下。

[INFO] Scanning for projects...
[INFO]
[INFO] --------------------< net.biancheng.www:helloworld >--------------------
[INFO] Building helloworld 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:3.1.2:tree (default-cli) @ helloworld ---
[INFO] net.biancheng.www:helloworld:jar:0.0.1-SNAPSHOT
[INFO] \- org.springframework.boot:spring-boot-starter-web:jar:2.4.5:compile
[INFO]    +- org.springframework.boot:spring-boot-starter:jar:2.4.5:compile
[INFO]    |  +- org.springframework.boot:spring-boot:jar:2.4.5:compile
[INFO]    |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.4.5:compile
[INFO]    |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.4.5:compile
[INFO]    |  |  +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO]    |  |  |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO]    |  |  |  \- org.slf4j:slf4j-api:jar:1.7.30:compile
[INFO]    |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.13.3:compile
[INFO]    |  |  |  \- org.apache.logging.log4j:log4j-api:jar:2.13.3:compile
[INFO]    |  |  \- org.slf4j:jul-to-slf4j:jar:1.7.30:compile
[INFO]    |  +- jakarta.annotation:jakarta.annotation-api:jar:1.3.5:compile
[INFO]    |  +- org.springframework:spring-core:jar:5.3.6:compile
[INFO]    |  |  \- org.springframework:spring-jcl:jar:5.3.6:compile
[INFO]    |  \- org.yaml:snakeyaml:jar:1.27:compile
[INFO]    +- org.springframework.boot:spring-boot-starter-json:jar:2.4.5:compile
[INFO]    |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.11.4:compile
[INFO]    |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.11.4:compile
[INFO]    |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.11.4:compile
[INFO]    |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.11.4:compile
[INFO]    |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.11.4:compile
[INFO]    |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.11.4:compile
[INFO]    +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.4.5:compile
[INFO]    |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:9.0.45:compile
[INFO]    |  +- org.glassfish:jakarta.el:jar:3.0.3:compile
[INFO]    |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:9.0.45:compile
[INFO]    +- org.springframework:spring-web:jar:5.3.6:compile
[INFO]    |  \- org.springframework:spring-beans:jar:5.3.6:compile
[INFO]    \- org.springframework:spring-webmvc:jar:5.3.6:compile
[INFO]       +- org.springframework:spring-aop:jar:5.3.6:compile
[INFO]       +- org.springframework:spring-context:jar:5.3.6:compile
[INFO]       \- org.springframework:spring-expression:jar:5.3.6:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.505 s
[INFO] Finished at: 2021-04-30T14:52:30+08:00
[INFO] ------------------------------------------------------------------------

从以上结果中,我们可以看到 Spring Boot 导入了 springframework、logging、jackson 以及 Tomcat 等依赖,而这些正是我们在开发 Web 项目时所需要的。

您可能会发现一个问题,即在以上 pom.xml 的配置中,引入依赖 spring-boot-starter-web 时,并没有指明其版本(version),但在依赖树中,我们却看到所有的依赖都具有版本信息,那么这些版本信息是在哪里控制的呢?

其实,这些版本信息是由 spring-boot-starter-parent(版本仲裁中心) 统一控制的。

spring-boot-starter-parent

spring-boot-starter-parent 是所有 Spring Boot 项目的父级依赖,它被称为 Spring Boot 的版本仲裁中心,可以对项目内的部分常用依赖进行统一管理。

<!--SpringBoot父项目依赖管理-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.4.5</version>
    <relativePath/>
</parent>

Spring Boot 项目可以通过继承 spring-boot-starter-parent 来获得一些合理的默认配置,它主要提供了以下特性:

  • 默认 JDK 版本(Java 8)
  • 默认字符集(UTF-8)
  • 依赖管理功能
  • 资源过滤
  • 默认插件配置
  • 识别 application.properties 和 application.yml 类型的配置文件

查看 spring-boot-starter- parent 的底层代码,可以发现其有一个父级依赖 spring-boot-dependencies。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.4.5</version>
</parent>

spring-boot-dependencies 的底层代码如下。

?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.4.5</version>
    <packaging>pom</packaging>
    ....
    <properties>
        <activemq.version>5.16.1</activemq.version>
        <antlr2.version>2.7.7</antlr2.version>
        <appengine-sdk.version>1.9.88</appengine-sdk.version>
        <artemis.version>2.15.0</artemis.version>
        <aspectj.version>1.9.6</aspectj.version>
        <assertj.version>3.18.1</assertj.version>
        <atomikos.version>4.0.6</atomikos.version>
        ....
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-amqp</artifactId>
                <version>${activemq.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.activemq</groupId>
                <artifactId>activemq-blueprint</artifactId>
                <version>${activemq.version}</version>
            </dependency>
            ...
        </dependencies>
    </dependencyManagement>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>build-helper-maven-plugin</artifactId>
                    <version>${build-helper-maven-plugin.version}</version>
                </plugin>
                <plugin>
                    <groupId>org.flywaydb</groupId>
                    <artifactId>flyway-maven-plugin</artifactId>
                    <version>${flyway.version}</version>
                </plugin>
                ...
            </plugins>
        </pluginManagement>
    </build>
</project>

以上配置中,部分元素说明如下:

  • dependencyManagement :负责管理依赖;
  • pluginManagement:负责管理插件;
  • properties:负责定义依赖或插件的版本号。

spring-boot-dependencies 通过 dependencyManagement 、pluginManagement 和 properties 等元素对一些常用技术框架的依赖或插件进行了统一版本管理,例如 Activemq、Spring、Tomcat 等。

YAML教程

Spring Boot 提供了大量的自动配置,极大地简化了spring 应用的开发过程,当用户创建了一个 Spring Boot 项目后,即使不进行任何配置,该项目也能顺利的运行起来。当然,用户也可以根据自身的需要使用配置文件修改 Spring Boot 的默认设置。

SpringBoot 默认使用以下 2 种全局的配置文件,其文件名是固定的。

  • application.properties
  • application.yml

其中,application.yml 是一种使用 YAML 语言编写的文件,它与 application.properties 一样,可以在 Spring Boot 启动时被自动读取,修改 Spring Boot 自动配置的默认值。

YAML 简介

YAML 全称 YAML Ain’t Markup Language,它是一种以数据为中心的标记语言,比 XML 和 JSON 更适合作为配置文件。

想要使用 YAML 作为属性配置文件(以 .yml 或 .yaml 结尾),需要将 SnakeYAML 库添加到 classpath 下,Spring Boot 中的 spring-boot-starter-web 或 spring-boot-starter 都对 SnakeYAML 库做了集成, 只要项目中引用了这两个 Starter 中的任何一个,Spring Boot 会自动添加 SnakeYAML 库到 classpath 下。

下面是一个简单的 application.yml 属性配置文件。

server:  
    port: 8081

YAML 语法

YAML 的语法如下:

  • 使用缩进表示层级关系。
  • 缩进时不允许使用 Tab 键,只允许使用空格。
  • 缩进的空格数不重要,但同级元素必须左侧对齐。
  • 大小写敏感。

例如:

spring:
  profiles: dev
  datasource:
    url: jdbc:mysql://127.0.01/banchengbang_springboot
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

YAML 常用写法

YAML 支持以下三种数据结构:

  • 对象:键值对的集合
  • 数组:一组按次序排列的值
  • 字面量:单个的、不可拆分的值

YAML 字面量写法

字面量是指单个的,不可拆分的值,例如:数字、字符串、布尔值、以及日期等。

在 YAML 中,使用“key:[空格]value的形式表示一对键值对(空格不能省略),如 url: www.biancheng.net

字面量直接写在键值对的“value中即可,且默认情况下字符串是不需要使用单引号或双引号的。

name: bianchengbang

若字符串使用单引号,则会转义特殊字符。

name: zhangsan \n lisi

输出结果为:

zhangsan \n lisi

若字符串使用双引号,则不会转义特殊字符,特殊字符会输出为其本身想表达的含义

name: zhangsan \n lisi

输出结果为:

zhangsan 
lisi

YAML 对象写法

在 YAML 中,对象可能包含多个属性,每一个属性都是一对键值对。
YAML 为对象提供了 2 种写法:

普通写法,使用缩进表示对象与属性的层级关系。

website: 
  name: bianchengbang
  url: www.biancheng.net

行内写法:

website: {name: bianchengbang,url: www.biancheng.net}

YAML 数组写法

YAML 使用“-”表示数组中的元素,普通写法如下:

pets:
  -dog
  -cat
  -pig

行内写法

pets: [dog,cat,pig]

复合结构

以上三种数据结构可以任意组合使用,以实现不同的用户需求,例如:

person:
  name: zhangsan
  age: 30
  pets:
    -dog
    -cat
    -pig
  car:
    name: QQ
  child:
    name: zhangxiaosan
    age: 2

YAML 组织结构

一个 YAML 文件可以由一个或多个文档组成,文档之间使用“—作为分隔符,且个文档相互独立,互不干扰。如果 YAML 文件只包含一个文档,则“—分隔符可以省略。

---
website:
  name: bianchengbang
  url: www.biancheng.net
---
website: {name: bianchengbang,url: www.biancheng.net}
pets:
  -dog
  -cat
  -pig
---
pets: [dog,cat,pig]
name: "zhangsan \n lisi"
---
name: 'zhangsan \n lisi'

Spring Boot配置绑定

注解:JavaBeans

所谓“配置绑定”就是把配置文件中的值与 JavaBean 中对应的属性进行绑定。通常,我们会把一些配置信息(例如,数据库配置)放在配置文件中,然后通过 Java 代码去读取该配置文件,并且把配置文件中指定的配置封装到 JavaBean(实体类) 中。

SpringBoot 提供了以下 2 种方式进行配置绑定:

  • 使用 @ConfigurationProperties 注解
  • 使用 @Value 注解

@ConfigurationProperties

通过 Spring Boot 提供的 @ConfigurationProperties 注解,可以将全局配置文件中的配置数据绑定到 JavaBean 中。下面我们以 Spring Boot 项目 helloworld 为例,演示如何通过 @ConfigurationProperties 注解进行配置绑定。

  1. 在 helloworld 的全局配置文件 application.yml 中添加以下自定义属性。
person:
  lastName: 张三
  age: 18
  boss: false
  birth: 1990/12/12
  maps: { k1: v1,k2: 12 }
  lists:
    ‐ lisi
    ‐ zhaoliu
  dog:
    name: 迪迪
    age: 5
  1. 在 helloworld 项目的 net.biancheng.www.bean 中创建一个名为 Person 的实体类,并将配置文件中的属性映射到这个实体类上,代码如下。
package net.biancheng.www.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
*
* @ConfigurationProperties:告诉 SpringBoot 将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能使用容器提供的@ConfigurationProperties功能;
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    public Person() {
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Boolean getBoss() {
        return boss;
    }
    public void setBoss(Boolean boss) {
        this.boss = boss;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Map<String, Object> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }
    public List<Object> getLists() {
        return lists;
    }
    public void setLists(List<Object> lists) {
        this.lists = lists;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public Person(String lastName, Integer age, Boolean boss, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.boss = boss;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }
    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}

注意:

  • 只有在容器中的组件,才会拥有 SpringBoot 提供的强大功能。如果我们想要使用 @ConfigurationProperties 注解进行配置绑定,那么首先就要保证该对 JavaBean 对象在 IoC 容器中,所以需要用到 @Component 注解来添加组件到容器中。
  • JavaBean 上使用了注解 @ConfigurationProperties(prefix = “person”) ,它表示将这个 JavaBean 中的所有属性与配置文件中以“person”为前缀的配置进行绑定。
  1. 在 net.biancheng.www.bean 中,创建一个名为 Dog 的 JavaBean,代码如下。
package net.biancheng.www.bean;
public class Dog {
    private String name;
    private String age;
    public Dog() {
    }
    public Dog(String name, String age) {
        this.name = name;
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public String getAge() {
        return age;
    }
}
  1. 修改 HelloController 的代码,在浏览器中展示配置文件中各个属性值,代码如下。
package net.biancheng.www.controller;
import net.biancheng.www.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
    @Autowired
    private Person person;
    @ResponseBody
    @RequestMapping("/hello")
    public Person hello() {
        return person;
    }
}
  1. 重启项目,使用浏览器访问 “http://localhost:8081/hello”,结果如下图。

@Value

当我们只需要读取配置文件中的某一个配置时,可以通过 @Value 注解获取。

  1. 以 Spring Boot 项目 helloworld 为例,修改实体类 Person 中的代码,使用 @Value 注解进行配置绑定,代码如下。
package net.biancheng.www.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Component
public class Person {
    @Value("${person.lastName}")
    private String lastName;
    @Value("${person.age}")
    private Integer age;
    @Value("${person.boss}")
    private Boolean boss;
    @Value("${person.birth}")
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    public Person() {
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Boolean getBoss() {
        return boss;
    }
    public void setBoss(Boolean boss) {
        this.boss = boss;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Map<String, Object> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }
    public List<Object> getLists() {
        return lists;
    }
    public void setLists(List<Object> lists) {
        this.lists = lists;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public Person(String lastName, Integer age, Boolean boss, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.boss = boss;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }
    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}
  1. 重启项目,使用浏览器访问 “http://localhost:8081/hello”,结果如下图。

@Value 与 @ConfigurationProperties 对比

@Value 和 @ConfigurationProperties 注解都能读取配置文件中的属性值并绑定到 JavaBean 中,但两者存在以下不同。

1. 使用位置不同

  • @ConfigurationProperties:标注在 JavaBean 的类名上;
  • @Value:标注在 JavaBean 的属性上。

2. 功能不同

  • @ConfigurationProperties:用于批量绑定配置文件中的配置;
  • @Value:只能一个一个的指定需要绑定的配置。

3. 松散绑定支持不同

@ConfigurationProperties:支持松散绑定(松散语法),例如实体类 Person 中有一个属性为 lastName,那么配置文件中的属性名支持以下写法:

  • person.firstName
  • person.first-name
  • person.first_name
  • PERSON_FIRST_NAME

@Vaule:不支持松散绑定。

4. SpEL 支持不同

  • @ConfigurationProperties:不支持 SpEL 表达式;
  • @Value:支持 SpEL 表达式。

5. 复杂类型封装

  • @ConfigurationProperties:支持所有类型数据的封装,例如 Map、List、Set、以及对象等;
  • @Value:只支持基本数据类型的封装,例如字符串、布尔值、整数等类型。

6. 应用场景不同

@Value 和 @ConfigurationProperties 两个注解之间,并没有明显的优劣之分,它们只是适合的应用场景不同而已。

  • 若只是获取配置文件中的某项值,则推荐使用 @Value 注解;
  • 若专门编写了一个 JavaBean 来和配置文件进行映射,则建议使用 @ConfigurationProperties 注解。

我们在选用时,根据实际应用场景选择合适的注解能达到事半功倍的效果。

@PropertySource

如果将所有的配置都集中到 application.properties 或 application.yml 中,那么这个配置文件会十分的臃肿且难以维护,因此我们通常会将与 Spring Boot 无关的配置(例如自定义配置)提取出来,写在一个单独的配置文件中,并在对应的 JavaBean 上使用 @PropertySource 注解指向该配置文件。

  1. 以 helloworld 为例,将与 person 相关的自定义配置移动到 src/main/resources 下的 person.properties 中(注意,必须把 application.properties 或 application.yml 中的相关配置删除),如下图。

person.properties 的配置如下。

person.last-name=李四
person.age=12
person.birth=2000/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=14
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2
  1. 在 Person 使用 @PropertySource 注解指向 person.properties,代码如下。
package net.biancheng.www.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
@PropertySource(value = "classpath:person.properties")//指向对应的配置文件
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    public Person() {
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public Boolean getBoss() {
        return boss;
    }
    public void setBoss(Boolean boss) {
        this.boss = boss;
    }
    public Date getBirth() {
        return birth;
    }
    public void setBirth(Date birth) {
        this.birth = birth;
    }
    public Map<String, Object> getMaps() {
        return maps;
    }
    public void setMaps(Map<String, Object> maps) {
        this.maps = maps;
    }
    public List<Object> getLists() {
        return lists;
    }
    public void setLists(List<Object> lists) {
        this.lists = lists;
    }
    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    public Person(String lastName, Integer age, Boolean boss, Date birth, Map<String, Object> maps, List<Object> lists, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.boss = boss;
        this.birth = birth;
        this.maps = maps;
        this.lists = lists;
        this.dog = dog;
    }
    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }
}
  1. 重启项目,使用浏览器访问 “http://localhost:8081/hello”,结果如下图。

Spring Boot导入Spring配置

默认情况下,Spring Boot 中是不包含任何的 Spring 配置文件的,即使我们手动添加 Spring 配置文件到项目中,也不会被识别。那么 Spring Boot 项目中真的就无法导入 Spring 配置吗?答案是否定的。

Spring Boot 为了我们提供了以下 2 种方式来导入 Spring 配置:

  • 使用 @ImportResource 注解加载 Spring 配置文件
  • 使用全注解方式加载 Spring 配置

@ImportResource 导入 Spring 配置文件

在主启动类上使用 @ImportResource 注解可以导入一个或多个 Spring 配置文件,并使其中的内容生效。

  1. 以 helloworld 为例,在 net.biancheng.www.service 包下创建一个名为 PersonService 的接口,代码如下。
package net.biancheng.www.service;
import net.biancheng.www.bean.Person;
public interface PersonService {
    public Person getPersonInfo();
}
  1. net.biancheng.www.service.impl 包下创建一个名为 PersonServiceImpl 的类,并实现 PersonService 接口,代码如下。
package net.biancheng.www.service.impl;
import net.biancheng.www.bean.Person;
import net.biancheng.www.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
public class PersonServiceImpl implements PersonService {
    @Autowired
    private Person person;
    @Override
    public Person getPersonInfo() {
        return person;
    }
}
  1. 在该项目的 resources 下添加一个名为 beans.xml 的 Spring 配置文件,配置代码如下。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="personService" class="net.biancheng.www.service.impl.PersonServiceImpl"></bean>
</beans>
  1. 修改该项目的单元测试类 HelloworldApplicationTests ,校验 IOC 容器是否已经 personService,代码如下。
package net.biancheng.www;
import net.biancheng.www.bean.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
@SpringBootTest
class HelloworldApplicationTests {
    @Autowired
    Person person;
    //IOC 容器
    @Autowired
    ApplicationContext ioc;
    @Test
    public void testHelloService() {
        //校验 IOC 容器中是否包含组件 personService
        boolean b = ioc.containsBean("personService");
        if (b) {
            System.out.println("personService 已经添加到 IOC 容器中");
        } else {
            System.out.println("personService 没添加到 IOC 容器中");
        }
    }
    @Test
    void contextLoads() {
        System.out.println(person);
    }
}
  1. 运行单元测试代码,结果如下图。

  1. 在主启动程序类上使用 @ImportResource 注解,将 Spring 配置文件 beans.xml 加载到项目中,代码如下。
package net.biancheng.www;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
//将 beans.xml 加载到项目中
@ImportResource(locations = {"classpath:/beans.xml"})
@SpringBootApplication
public class HelloworldApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }
}
  1. 再次执行测试代码,结果如下图。

全注解方式加载 Spring 配置

Spring Boot 推荐我们使用全注解的方式加载 Spring 配置,其实现方式如下:

  1. 使用 @Configuration 注解定义配置类,替换 Spring 的配置文件;
  2. 配置类内部可以包含有一个或多个被 @Bean 注解的方法,这些方法会被 AnnotationConfigApplicationContext 或 AnnotationConfigWebApplicationContext 类扫描,构建 bean 定义(相当于 Spring 配置文件中的<bean></bean>标签),方法的返回值会以组件的形式添加到容器中,组件的 id 就是方法名。

以 helloworld 为例,删除主启动类的 @ImportResource 注解,在 net.biancheng.www.config 包下添加一个名为 MyAppConfig 的配置类,代码如下。

package net.biancheng.www.config;
import net.biancheng.www.service.PersonService;
import net.biancheng.www.service.impl.PersonServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Configuration 注解用于定义一个配置类,相当于 Spring 的配置文件
* 配置类中包含一个或多个被 @Bean 注解的方法,该方法相当于 Spring 配置文件中的 <bean> 标签定义的组件。
*/
@Configuration
public class MyAppConfig {
    /**
     * 与 <bean id="personService" class="PersonServiceImpl"></bean> 等价
     * 该方法返回值以组件的形式添加到容器中
     * 方法名是组件 id(相当于 <bean> 标签的属性 id)
     */
    @Bean
    public PersonService personService() {
        System.out.println("在容器中添加了一个组件:peronService");
        return new PersonServiceImpl();
    }
}

执行测试代码,执行结果如下图。

Spring Boot Profile(多环境配置)

在实际的项目开发中,一个项目通常会存在多个环境,例如,开发环境、测试环境和生产环境等。不同环境的配置也不尽相同,例如开发环境使用的是开发数据库,测试环境使用的是测试数据库,而生产环境使用的是线上的正式数据库。

Profile 为在不同环境下使用不同的配置提供了支持,我们可以通过激活、指定参数等方式快速切换环境。

多 Profile 文件方式

Spring Boot 的配置文件共有两种形式:.properties 文件和 .yml 文件,不管哪种形式,它们都能通过文件名的命名形式区分出不同的环境的配置,文件命名格式为:

application-{profile}.properties/yml

其中,{profile} 一般为各个环境的名称或简称,例如 dev、test 和 prod 等等。

properties 配置

在 helloworld 的 src/main/resources 下添加 4 个配置文件:

  • application.properties:主配置文件
  • application-dev.properties:开发环境配置文件
  • application-test.properties:测试环境配置文件
  • application-prod.properties:生产环境配置文件

在 applcation.properties 文件中,指定默认服务器端口号为 8080,并通过以下配置激活生产环境(prod)的 profile。

#默认端口号
server.port=8080
#激活指定的profile
spring.profiles.active=prod

在 application-dev.properties 中,指定开发环境端口号为 8081,配置如下

# 开发环境
server.port=8081

在 application-test.properties 中,指定测试环境端口号为 8082,配置如下。

# 测试环境
server.port=8082

在 application-prod.properties 中,指定生产环境端口号为 8083,配置如下。

# 生产环境
server.port=8083

重启 Spring Boot 主启动程序,控制台输出如下图。

通过上图可以看到,我们指定的生产环境(prod) Profile 生效了,且服务器端口为 8083。

yml 配置

与 properties 文件类似,我们也可以添加 4 个配置文件:

  • application.yml:默认配置
  • application-dev.yml:开发环境配置
  • application-test.yml:测试环境配置
  • application-prod.yml:生产环境配置

在 applcation.yml 文件中指定默认服务端口号为 8080,并通过以下配置来激活开发环境的 profile。

#默认配置
server:
  port: 8080
#切换配置
spring:
  profiles:
    active: dev #激活开发环境配置

在 application-dev.yml 中指定开发环境端口号为 8081,配置如下。

#开发环境
server: 
    port: 8081

在 application-test.yml 中指定测试环境端口号为 8082,配置如下。

#测试环境
server:  
    port: 8082

在 application-prod.yml 中指定生产环境端口号为 8083,配置如下。

#生产环境
server:  
    port: 8083

重启 Spring Boot 主程序,查看控制台输出,如下图。

通过上图可以看到,我们指定的开发环境(dev) Profile 生效了,且服务器端口为 8081。

多 Profile 文档块模式

在 YAML 配置文件中,可以使用“—”把配置文件分割成了多个文档块,因此我们可以在不同的文档块中针对不同的环境进行不同的配置,并在第一个文档块内对配置进行切换。

以 helloworld 项目为例,修改 application.yml ,配置多个文档块,并在第一文档快内激活测试环境的 Profile,代码如下。

#默认配置
server:
  port: 8080
#切换配置
spring:
  profiles:
    active: test
---
#开发环境
server:
  port: 8081
spring:
  config:
    activate:
      on-profile: dev
---
#测试环境
server:
  port: 8082
spring:
  config:
    activate:
      on-profile: test
---
#生产环境
server:
  port: 8083
spring:
  config:
    activate:
      on-profile: prod

重启 Spring Boot 主启动程序,查看控制台输出,如下图。

通过上图可以看到,我们指定的测试环境(test) Profile 生效了,且服务器端口为 8082。

激活 Profile

除了可以在配置文件中激活指定 Profile,Spring Boot 还为我们提供了另外 2 种激活 Profile 的方式:

  • 命令行激活
  • 虚拟机参数激活

命令行激活

我们可以将 Spring Boot 项目打包成 JAR 文件,并在通过命令行运行时,配置命令行参数,激活指定的 Profile。

我们还以 helloworld 为例,执行以下 mvn 命令将项目打包。

mvn clean package

项目打包完成,结果如下图。

打开命令行窗口,跳转到 JAR 文件所在目录,执行以下命令,启动该项目,并激活开发环境(dev)的 Profile。

java -jar helloworld-0.0.1-SNAPSHOT.jar  --spring.profiles.active=dev

以上命令中,–spring.profiles.active=dev 为激活开发环境(dev)Profile 的命令行参数。

执行结果如下图。

虚拟机参数激活

我们还可以在 Spring Boot 项目运行时,指定虚拟机参数来激活指定的 Profile。

以 helloworld 为例,将该项目打包成 JAR 文件后,打开命令行窗口跳转到 JAR 所在目录,执行以下命令,激活生产环境(prod)Profile。

java -Dspring.profiles.active=prod -jar helloworld-0.0.1-SNAPSHOT.jar

以上命令中,-Dspring.profiles.active=prod 为激活生产环境(prod)Profile 的虚拟机参数。

执行结果如下图。

Spring Boot默认配置文件

常情况下,Spring Boot 在启动时会将 resources 目录下的 application.properties 或 apllication.yml 作为其默认配置文件,我们可以在该配置文件中对项目进行配置,但这并不意味着 Spring Boot 项目中只能存在一个 application.properties 或 application.yml。

默认配置文件

Spring Boot 项目中可以存在多个 application.properties 或 apllication.yml。

Spring Boot 启动时会扫描以下 5 个位置的 application.properties 或 apllication.yml 文件,并将它们作为 Spring boot 的默认配置文件。

  1. file:./config/
  2. file:./config/*/
  3. file:./
  4. classpath:/config/
  5. classpath:/

注:file: 指当前项目根目录;classpath: 指当前项目的类路径,即 resources 目录。

以上所有位置的配置文件都会被加载,且它们优先级依次降低,序号越小优先级越高。其次,位于相同位置的 application.properties 的优先级高于 application.yml。

所有位置的文件都会被加载,高优先级配置会覆盖低优先级配置,形成互补配置,即:

  • 存在相同的配置内容时,高优先级的内容会覆盖低优先级的内容;
  • 存在不同的配置内容时,高优先级和低优先级的配置内容取并集。

示例

创建一个名为 springbootdemo 的 Spring Boot 项目,并在当前项目根目录下、类路径下的 config 目录下、以及类路径下分别创建一个配置文件 application.yml,该项目结构如下图。

项目根路径下配置文件 application.yml 配置如下。

#项目更目录下
#上下文路径为 /abc
server:
  servlet:
    context-path: /abc

项目类路径下 config 目录下配置文件 application.yml 配置如下。

#类路径下的 config 目录下
#端口号为8084
#上下文路径为 /helloWorld
server:
  port: 8084
  servlet:
    context-path: /helloworld

项目类路径下的 application.yml 配置如下。

#默认配置
server:
  port: 8080

在 net.biancheng.www.controller 包下创建一个名为 MyController 的类,代码如下。

package net.biancheng.www.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
    @ResponseBody
    @RequestMapping("/test")
    public String hello() {
        return "hello Spring Boot!";
    }
}

启动 Spring Boot,查看控制台输出,如下图。

根据 Spring Boot 默认配置文件优先级进行分析:

  • 该项目中存在多个默认配置文件,其中根目录下 /config 目录下的配置文件优先级最高,因此项目的上下文路径为 “/abc”;
  • 类路径(classpath)下 config 目录下的配置文件优先级高于类路径下的配置文件,因此该项目的端口号为 “8084”;
  • 以上所有配置项形成互补,所以访问路径为“http://localhost:8084/abc”。

根据服务器端口和上下文路径,使用浏览器访问 http://localhost:8084/abc/test,结果如下图。

Spring Boot外部配置文件

除了默认配置文件,Spring Boot 还可以加载一些位于项目外部的配置文件。我们可以通过如下 2 个参数,指定外部配置文件的路径:

  • spring.config.location
  • spring.config.additional-location

spring.config.location

我们可以先将 Spring Boot 项目打包成 JAR 文件,然后在命令行启动命令中,使用命令行参数 –spring.config.location,指定外部配置文件的路径。

java -jar {JAR}  --spring.config.location={外部配置文件全路径}

需要注意的是,使用该参数指定配置文件后,会使项目默认配置文件(application.properties 或 application.yml )失效,Spring Boot 将只加载指定的外部配置文件。

示例 1

  1. 在本地目录 D:\myConfig 下,创建一个配置文件 my-application.yml,配置如下。
#指定配置文件
server:  
    port: 8088
  1. 执行以下 mvn 命令,将 springbootdemo 项目打包成 JAR。
mvn clean package

命令执行结果如下图。

  1. 打开命令行窗口,跳转到 JAR 文件所在目录,执行以下命令,其中 –spring.config.location 用于指定配置文件的新位置。
java -jar springbootdemo-0.0.1-SNAPSHOT.jar  --spring.config.location=D:\myConfig\my-application.yml

项目运行结果如下图。

从控制台输出可以看出:

  • 服务器端口号从“8084”被修改为“8088”,表示外部配置文件已生效;
  • 上下文路径则从“/abc”被修改为默认值(‘ ’),表示项目内部的默认配置文件已失效。
  1. 使用浏览器访问 “http://localhost:8088/test”,结果如下图。

spring.config.additional-location

我们还可以在 Spring Boot 启动时,使用命令行参数 –spring.config.additional-location 来加载外部配置文件。

java -jar {JAR}  --spring.config.additional-location={外部配置文件全路径}

但与 –spring.config.location 不同,–spring.config.additional-location 不会使项目默认的配置文件失效,使用该命令行参数添加的外部配置文件会与项目默认的配置文件共同生效,形成互补配置,且其优先级是最高的,比所有默认配置文件的优先级都高。

示例 2

  1. 将 springbootdemo 打包为 JAR 文件,打开命令行窗口,跳转到该项目 JAR 所在目录下,执行以下命令启动该项目。
java -jar springbootdemo-0.0.1-SNAPSHOT.jar  --spring.config.additional-location=D:\myConfig\my-application.yml

结果如下图。

注意:Maven 对项目进行打包时,位于项目根目录下的配置文件是无法被打包进项目的 JAR 包的,因此位于根目录下的默认配置文件无法在 JAR 中生效,即该项目将只加载指定的外部配置文件和项目类路径(classpath)下的默认配置文件,它们的加载优先级顺序为:

  1. spring.config.additional-location 指定的外部配置文件 my-application.yml
  2. classpath:/config/application.yml
  3. classpath:/application.yml

根据配置文件优先级分析可知:

  • 以上三个配置文件中 my-application.yml 的优先级最高,因此该项目的服务器端口号为 “8088”;
  • 只有 classpath:/config/application.yml 中配置了上下文路径(context-path),因此该项目的上下文路径为 “/helloworld”;
  • 基于以上配置分析,得出该项目访问路径为“http://localhost:8088/helloWorld”。
  1. 使用浏览器访问 “http://localhost:8088/helloworld/test”,结果如下图。

通过上面的示例,我们看到将 Spring Boot 项目打包后,然后在命令行启动命令中添加 spring.config.additional-location 参数指定外部配置文件,会导致项目根目录下的配置文件无法被加载,我们可以通过以下 3 种方式解决这个问题。

  • 在 IDEA 的运行配置(Run/Debug Configuration)中,添加虚拟机参数 -Dspring.config.additional-location=D:\myConfig\my-application.yml,指定外部配置文件;

  • 在 IDEA 的运行配置(Run/Debug Configuration)中,添加程序运行参数 –spring.config.additional-location=D:\myConfig\my-application.yml,指定外部配置文件;

  • 在主启动类中调用 System.setProperty()方法添加系统属性 spring.config.additional-location,指定外部配置文件。

Spring Boot配置加载顺序

Spring Boot 不仅可以通过配置文件进行配置,还可以通过环境变量、命令行参数等多种形式进行配置。这些配置都可以让开发人员在不修改任何代码的前提下,直接将一套 Spring Boot 应用程序在不同的环境中运行。

Spring Boot 配置优先级

以下是常用的 Spring Boot 配置形式及其加载顺序(优先级由高到低):

  1. 命令行参数
  2. 来自 java:comp/env 的 JNDI 属性
  3. Java 系统属性(System.getProperties())
  4. 操作系统环境变量
  5. RandomValuePropertySource 配置的 random.* 属性值
  6. 配置文件(YAML 文件、Properties 文件)
  7. @Configuration 注解类上的 @PropertySource 指定的配置文件
  8. 通过 SpringApplication.setDefaultProperties 指定的默认属性

以上所有形式的配置都会被加载,当存在相同配置内容时,高优先级的配置会覆盖低优先级的配置;存在不同的配置内容时,高优先级和低优先级的配置内容取并集,共同生效,形成互补配置。

命令行参数

Spring Boot 中的所有配置,都可以通过命令行参数进行指定,其配置形式如下。

java -jar {Jar文件名} --{参数1}={参数值1} --{参数2}={参数值2}

示例 1

  1. 在 springbootdemo 项目启动时,使用以下命令。
java -jar springbootdemo-0.0.1-SNAPSHOT.jar --server.port=8081 --server.servlet.context-path=/bcb

命令行参数说明如下:

  • –server.port:指定服务器端口号;
  • –server.servlet.context-path:指定上下文路径(项目的访问路径)。

执行结果如下图。

配置文件

Spring Boot 启动时,会自动加载 JAR 包内部及 JAR 包所在目录指定位置的配置文件(Properties 文件、YAML 文件),下图中展示了 Spring Boot 自动加载的配置文件的位置及其加载顺序,同一位置下,Properties 文件优先级高于 YAML 文件。

图说明如下:

  • /myBoot:表示 JAR 包所在目录,目录名称自定义;
  • /childDir:表示 JAR 包所在目录下 config 目录的子目录,目录名自定义;
  • JAR:表示 Spring Boot 项目打包生成的 JAR;
  • 其余带有“/”标识的目录的目录名称均不能修改。
  • 红色数字:表示该配置文件的优先级,数字越小优先级越高。

这些配置文件得优先级顺序,遵循以下规则:

  1. 先加载 JAR 包外的配置文件,再加载 JAR 包内的配置文件;
  2. 先加载 config 目录内的配置文件,再加载 config 目录外的配置文件;
  3. 先加载 config 子目录下的配置文件,再加载 config 目录下的配置文件;
  4. 先加载 appliction-{profile}.properties/yml,再加载 application.properties/yml;
  5. 先加载 .properties 文件,再加载 .yml 文件。

示例 2

  1. 创建一个名为 mybootdemo 的 Spring Boot 项目,并在 src/main/resoources 下创建以下 4 个配置文件。
  • application.yml:默认配置
  • application-dev.yml:开发环境配置
  • application-test.yml:测试环境配置
  • application-prod.yml:生产环境配置

1)在 applcation.yml 文件中,指定默认服务端口号(port)为 “8080”,上下文路径(context-path)为“/mybootdemo”,并激活开发环境(dev)的 profile。

server:
  port: 8080 #端口号
  servlet:
    context-path: /mybootdemo #上下文路径或项目访问路径
spring:
  profiles:
    active: dev #激活开发环境配置

2)在 application-dev.yml 中,指定开发环境端口号为 “8081”,上下文路径为“/in-dev”,配置如下。

server:
  port: 8081 #开发环境端口号 8081
  servlet:
    context-path: /in-dev #开发环境上下文路径为 in-dev
spring:
  config:
    activate:
      on-profile: dev #开发环境

3)在 application-test.yml 中,指定测试环境端口号为 “8082”,上下文路径为“/in-test”,配置如下。

#测试环境配置
server:
  port: 8082 #测试环境端口 8082
  servlet:
    context-path: /in-test #测试环境上下文路径 /in-test
spring:
  config:
    activate:
      on-profile: test

4)在 application-prod.yml 中,指定生产环境端口号为 “8083”,上下文路径为“/in-prod”,配置如下。

#生产环境配置
server:
  port: 8083 #端口号
  servlet:
    context-path: /in-prod #上下文路径
spring:
  config:
    activate:
      on-profile: prod
  1. 执行以下 mvn 命令,将 mybootdemo 打包成 JAR,并将该 JAR 包移动到本次磁盘的某个目录下(例如 mySpringBoot 目录)。
mvn clean package
  1. 在 JAR 包所在目录下创建 application.yml ,并设置上下文路径为“/out-default”,并激活生产环境(prod)Profile。
#JAR 包外默认配置
server:
  servlet:
    context-path: /out-default
#切换配置
spring:
  profiles:
    active: prod #激活开发环境配置
  1. 打开命令行窗口,跳转到 mySpringBoot 目录下,执行以下命令启动 Spring Boot。
java -jar mybootdemo-0.0.1-SNAPSHOT.jar

启动结果如下图。

示例分析:

  • Spring Boot 在启动时会加载全部的 5 个配置文件,其中位于 JAR 包外的 application.yml 优先级最高;
  • 在 JAR 包外的 application.yml 中,配置激活了生产环境(prod)Profile,即 JAR 包内部的 application-prod.yml 生效。此时,该项目中的配置文件优先级顺序为:JAR 包外 application.yml > JAR 包内 application-prod.yml >JAR 包内其他配置文件;
  • application-prod.yml 的配置内容会覆盖 JAR 包内所有其他配置文件的配置内容,即端口号(port)为“8083”,上下文路径(context-path)为“/in-prod”;
  • JAR 包内的 application-prod.yml 中的上下文路径会被 JAR 包外的 application.yml 覆盖为“/out-default”;
  • JAR 包内的 application-prod.yml 与 JAR 包外的 application.yml,形成互补配置,即,端口号为“8083”,上下文路径为“/out-default”。

Spring Boot自动配置原理

我们知道,Spring Boot 项目创建完成后,即使不进行任何的配置,也能够顺利地运行,这都要归功于 Spring Boot 的自动化配置。

Spring Boot 默认使用 application.properties 或 application.yml 作为其全局配置文件,我们可以在该配置文件中对各种自动配置属性(server.port、logging.level.* 、spring.config.active.no-profile 等等)进行修改,并使之生效,那么您有没有想过这些属性是否有据可依呢?答案是肯定的。

Spring Boot 官方文档:常见应用属性中对所有的配置属性都进行了列举和解释,我们可以根据官方文档对 Spring Boot 进行配置,但 Spring Boot 中的配置属性数量庞大,仅仅依靠官方文档进行配置也十分麻烦。我们只有了解了 Spring Boot 自动配置的原理,才能更加轻松熟练地对 Spirng Boot 进行配置。本

Spring Factories 机制

Spring Boot 的自动配置是基于 Spring Factories 机制实现的。

Spring Factories 机制是 Spring Boot 中的一种服务发现机制,这种扩展机制与 Java SPI 机制十分相似。Spring Boot 会自动扫描所有 Jar 包类路径下 META-INF/spring.factories 文件,并读取其中的内容,进行实例化,这种机制也是 Spring Boot Starter 的基础。

spring.factories

spring.factories 文件本质上与 properties 文件相似,其中包含一组或多组键值对(key=vlaue),其中,key 的取值为接口的完全限定名;value 的取值为接口实现类的完全限定名,一个接口可以设置多个实现类,不同实现类之间使用“,”隔开,例如:

org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

注意:文件中配置的内容过长,为了阅读方便而手动换行时,为了防止内容丢失可以使用“\”。

Spring Factories 实现原理

spring-core 包里定义了 SpringFactoriesLoader 类,这个类会扫描所有 Jar 包类路径下的 META-INF/spring.factories 文件,并获取指定接口的配置。在 SpringFactoriesLoader 类中定义了两个对外的方法,如下表。

返回值 方法 描述
<T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) 静态方法; 根据接口获取其实现类的实例; 该方法返回的是实现类对象列表。
List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) 公共静态方法; 根据接口l获取其实现类的名称; 该方法返回的是实现类的类名的列表

以上两个方法的关键都是从指定的 ClassLoader 中获取 spring.factories 文件,并解析得到类名列表,具体代码如下。

loadFactories() 方法能够获取指定接口的实现类对象,具体代码如下。

public static <T> List<T> loadFactories(Class<T> factoryType, @Nullable ClassLoader classLoader) {
    Assert.notNull(factoryType, "'factoryType' must not be null");
    ClassLoader classLoaderToUse = classLoader;
    if (classLoader == null) {
        classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
    }
    // 调用loadFactoryNames获取接口的实现类
    List<String> factoryImplementationNames = loadFactoryNames(factoryType, classLoaderToUse);
    if (logger.isTraceEnabled()) {
        logger.trace("Loaded [" + factoryType.getName() + "] names: " + factoryImplementationNames);
    }
    // 遍历 factoryNames 数组,创建实现类的对象
    List<T> result = new ArrayList(factoryImplementationNames.size());
    Iterator var5 = factoryImplementationNames.iterator();
    //排序
    while(var5.hasNext()) {
        String factoryImplementationName = (String)var5.next();
        result.add(instantiateFactory(factoryImplementationName, factoryType, classLoaderToUse));
    }
    AnnotationAwareOrderComparator.sort(result);
    return result;
}

loadFactoryNames() 方法能够根据接口获取其实现类类名的集合,具体代码如下。

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    ClassLoader classLoaderToUse = classLoader;
    if (classLoader == null) {
        classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
    }
    String factoryTypeName = factoryType.getName();
    //获取自动配置类
    return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
}

loadSpringFactories() 方法能够读取该项目中所有 Jar 包类路径下 META-INF/spring.factories 文件的配置内容,并以 Map 集合的形式返回,具体代码如下。

private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
    Map<String, List<String>> result = (Map)cache.get(classLoader);
    if (result != null) {
        return result;
    } else {
        HashMap result = new HashMap();
    try {
        //扫描所有 Jar 包类路径下的 META-INF/spring.factories 文件
        Enumeration urls = classLoader.getResources("META-INF/spring.factories");
        while(urls.hasMoreElements()) {
                URL url = (URL)urls.nextElement();
                UrlResource resource = new UrlResource(url);
                //将扫描到的 META-INF/spring.factories 文件中内容包装成 properties 对象
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                Iterator var6 = properties.entrySet().iterator();
                while(var6.hasNext()) {
                    Map.Entry<?, ?> entry = (Map.Entry)var6.next();
                    //提取 properties 对象中的 key 值
                    String factoryTypeName = ((String)entry.getKey()).trim();
                    //提取 proper 对象中的 value 值(多个类的完全限定名使用逗号连接的字符串)
                    // 使用逗号为分隔符转换为数组,数组内每个元素都是配置类的完全限定名
                    String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                    String[] var10 = factoryImplementationNames;
                    int var11 = factoryImplementationNames.length;
                    //遍历配置类数组,并将数组转换为 list 集合
                    for(int var12 = 0; var12 < var11; ++var12) {
                        String factoryImplementationName = var10[var12];
                        ((List)result.computeIfAbsent(factoryTypeName, (key) -> {
                            return new ArrayList();
                        })).add(factoryImplementationName.trim());
                    }
                }
            }
            //将 propertise 对象的 key 与由配置类组成的 List 集合一一对应存入名为 result 的 Map 中
            result.replaceAll((factoryType, implementations) -> {
                return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
            });
            cache.put(classLoader, result);
            //返回 result
            return result;
        } catch (IOException var14) {
            throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
        }
     }
}

自动配置的加载

Spring Boot 自动化配置也是基于 Spring Factories 机制实现的,在 spring-boot-autoconfigure-xxx.jar 类路径下的 META-INF/spring.factories 中设置了 Spring Boot 自动配置的内容 ,如下。

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.neo4j.Neo4jAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

以上配置中,value 取值是由多个 xxxAutoConfiguration (使用逗号分隔)组成,每个 xxxAutoConfiguration 都是一个自动配置类。Spring Boot 启动时,会利用 Spring-Factories 机制,将这些 xxxAutoConfiguration 实例化并作为组件加入到容器中,以实现 Spring Boot 的自动配置。

@SpringBootApplication 注解

所有 Spring Boot 项目的主启动程序类上都使用了一个 @SpringBootApplication 注解,该注解是 Spring Boot 中最重要的注解之一 ,也是 Spring Boot 实现自动化配置的关键。

@SpringBootApplication 是一个组合元注解,其主要包含两个注解:@SpringBootConfiguration 和 @EnableAutoConfiguration,其中 @EnableAutoConfiguration 注解是 SpringBoot 自动化配置的核心所在。

@EnableAutoConfiguration 注解

@EnableAutoConfiguration 注解用于开启 Spring Boot 的自动配置功能, 它使用 Spring 框架提供的 @Import 注解通过 AutoConfigurationImportSelector类(选择器)给容器中导入自动配置组件。

AutoConfigurationImportSelector 类

AutoConfigurationImportSelector 类实现了 DeferredImportSelector 接口,AutoConfigurationImportSelector 中还包含一个静态内部类 AutoConfigurationGroup,它实现了 DeferredImportSelector 接口的内部接口 Group(Spring 5 新增)。

AutoConfigurationImportSelector 类中包含 3 个方法,如下表。

返回值 方法声明 描述 内部类方法 内部类
Class<? extends Group> getImportGroup() 该方法获取实现了 Group 接口的类,并实例化
void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) 该方法用于引入自动配置的集合 AutoConfigurationGroup
Iterable<Entry> selectImports() 遍历自动配置类集合(Entry 类型的集合),并逐个解析集合中的配置类 AutoConfigurationGroup

AutoConfigurationImportSelector 内各方法执行顺序如下。

  1. getImportGroup() 方法
  2. process() 方法
  3. selectImports() 方法

下面我们将分别对以上 3 个方法及其调用过程进行介绍。

1. getImportGroup() 方法

AutoConfigurationImportSelector 类中 getImportGroup() 方法主要用于获取实现了 DeferredImportSelector.Group 接口的类,代码如下。

 public Class<? extends Group> getImportGroup() {
        //获取实现了 DeferredImportSelector.Gorup 接口的 AutoConfigurationImportSelector.AutoConfigurationGroup 类
        return AutoConfigurationImportSelector.AutoConfigurationGroup.class;
    }

2. process() 方法

静态内部类 AutoConfigurationGroup 中的核心方法是 process(),该方法通过调用 getAutoConfigurationEntry() 方法读取 spring.factories 文件中的内容,获得自动配置类的集合,代码如下 。

public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
    Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector, () -> {
        return String.format("Only %s implementations are supported, got %s", AutoConfigurationImportSelector.class.getSimpleName(), deferredImportSelector.getClass().getName());
    });
    //拿到 META-INF/spring.factories中的EnableAutoConfiguration,并做排除、过滤处理
    //AutoConfigurationEntry里有需要引入配置类和排除掉的配置类,最终只要返回需要配置的配置类
    AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector)deferredImportSelector).getAutoConfigurationEntry(annotationMetadata);
    //加入缓存,List<AutoConfigurationEntry>类型
    this.autoConfigurationEntries.add(autoConfigurationEntry);
    Iterator var4 = autoConfigurationEntry.getConfigurations().iterator();
    while(var4.hasNext()) {
        String importClassName = (String)var4.next();
        //加入缓存,Map<String, AnnotationMetadata>类型
        this.entries.putIfAbsent(importClassName, annotationMetadata);
    }
}

getAutoConfigurationEntry() 方法通过调用 getCandidateConfigurations() 方法来获取自动配置类的完全限定名,并在经过排除、过滤等处理后,将其缓存到成员变量中,具体代码如下。

protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    } else {
        //获取注解元数据中的属性设置
        AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
        //获取自动配置类
        List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
        //删除list 集合中重复的配置类
        configurations = this.removeDuplicates(configurations);
        //获取飘出导入的配置类
        Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
        //检查是否还存在排除配置类
        this.checkExcludedClasses(configurations, exclusions);
        //删除排除的配置类
        configurations.removeAll(exclusions);
        //获取过滤器,过滤配置类
        configurations = this.getConfigurationClassFilter().filter(configurations);
        //出发自动化配置导入事件
        this.fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
    }
}

getCandidateConfigurations() 方法中,根据 Spring Factories 机制调用 SpringFactoriesLoader 的 loadFactoryNames() 方法,根据 EnableAutoConfiguration.class (自动配置接口)获取其实现类(自动配置类)的类名的集合,如下图。

  1. process() 方法 以上所有方法执行完成后,AutoConfigurationImportSelector.AutoConfigurationGroup#selectImports() 会将 process() 方法处理后得到的自动配置类,进行过滤、排除,最后将所有自动配置类添加到容器中。
public Iterable<DeferredImportSelector.Group.Entry> selectImports() {
    if (this.autoConfigurationEntries.isEmpty()) {
        return Collections.emptyList();
    } else {
        //获取所有需要排除的配置类
        Set<String> allExclusions = (Set)this.autoConfigurationEntries.stream().
                map(AutoConfigurationImportSelector.AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet());
        //获取所有经过自动化配置过滤器的配置类
        Set<String> processedConfigurations = (Set)this.autoConfigurationEntries.stream().map(AutoConfigurationImportSelector.
                AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream).collect(Collectors.toCollection(LinkedHashSet::new));
        //排除过滤后配置类中需要排除的类
        processedConfigurations.removeAll(allExclusions);
        return (Iterable)this.sortAutoConfigurations(processedConfigurations,
                this.getAutoConfigurationMetadata()).stream().map((importClassName) -> {
            return new DeferredImportSelector.Group.Entry((AnnotationMetadata)this.entries.get(importClassName), importClassName);
        }).collect(Collectors.toList());
    }
}

自动配置的生效和修改

spring.factories 文件中的所有自动配置类(xxxAutoConfiguration),都是必须在一定的条件下才会作为组件添加到容器中,配置的内容才会生效。这些限制条件在 Spring Boot 中以 @Conditional 派生注解的形式体现,如下表。

注解 生效条件
@ConditionalOnJava 应用使用指定的 Java 版本时生效
@ConditionalOnBean 容器中存在指定的 Bean 时生效
@ConditionalOnMissingBean 容器中不存在指定的 Bean 时生效
@ConditionalOnExpression 满足指定的 SpEL 表达式时生效
@ConditionalOnClass 存在指定的类时生效
@ConditionalOnMissingClass 不存在指定的类时生效
@ConditionalOnSingleCandidate 容器中只存在一个指定的 Bean 或这个 Bean 为首选 Bean 时生效
@ConditionalOnProperty 系统中指定属性存在指定的值时生效
@ConditionalOnResource 类路径下存在指定的资源文件时生效
@ConditionalOnWebApplication 当前应用是 web 应用时生效
@ConditionalOnNotWebApplication 当前应用不是 web 应用生效

下面我们以 ServletWebServerFactoryAutoConfiguration 为例,介绍 Spring Boot 自动配置是如何生效的。

ServletWebServerFactoryAutoConfiguration

ServletWebServerFactoryAutoConfiguration 代码如下。

@Configuration(   //表示这是一个配置类,与 xml 配置文件等价,也可以给容器中添加组件
        proxyBeanMethods = false
)
@AutoConfigureOrder(-2147483648)
@ConditionalOnClass({ServletRequest.class})//判断当前项目有没有 ServletRequest 这个类
@ConditionalOnWebApplication(// 判断当前应用是否是 web 应用,如果是,当前配置类生效 
type = Type.SERVLET
)
@EnableConfigurationProperties({ServerProperties.class})
//启动指定类的属性配置(ConfigurationProperties)功能;将配置文件中对应的值和 ServerProperties 绑定起来;并把 ServerProperties 加入到ioc容器中
@Import({ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, EmbeddedTomcat.class, EmbeddedJetty.class, EmbeddedUndertow.class})
public class ServletWebServerFactoryAutoConfiguration {
    public ServletWebServerFactoryAutoConfiguration() {
    }
    @Bean //给容器中添加一个组件,这个组件的某些值需要从properties中获取
    public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties, ObjectProvider<WebListenerRegistrar> webListenerRegistrars) {
        return new ServletWebServerFactoryCustomizer(serverProperties, (List) webListenerRegistrars.orderedStream().collect(Collectors.toList()));
    }
    @Bean
    @ConditionalOnClass(
            name = {"org.apache.catalina.startup.Tomcat"}
    )
    public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer(ServerProperties serverProperties) {
        return new TomcatServletWebServerFactoryCustomizer(serverProperties);
    }
    @Bean
    @ConditionalOnMissingFilterBean({ForwardedHeaderFilter.class})
    @ConditionalOnProperty(
            value = {"server.forward-headers-strategy"},
            havingValue = "framework"
    )
    public FilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter() {
        ForwardedHeaderFilter filter = new ForwardedHeaderFilter();
        FilterRegistrationBean<ForwardedHeaderFilter> registration = new FilterRegistrationBean(filter, new ServletRegistrationBean[0]);
        registration.setDispatcherTypes(DispatcherType.REQUEST, new DispatcherType[]{DispatcherType.ASYNC, DispatcherType.ERROR});
        registration.setOrder(-2147483648);
        return registration;
    }
    public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {
        private ConfigurableListableBeanFactory beanFactory;
        public BeanPostProcessorsRegistrar() {
        }
        public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
            if (beanFactory instanceof ConfigurableListableBeanFactory) {
                this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
            }
        }
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            if (this.beanFactory != null) {
                this.registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class, WebServerFactoryCustomizerBeanPostProcessor::new);
                this.registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class, ErrorPageRegistrarBeanPostProcessor::new);
            }
        }
        private <T> void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name, Class<T> beanClass, Supplier<T> instanceSupplier) {
            if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) {
                RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass, instanceSupplier);
                beanDefinition.setSynthetic(true);
                registry.registerBeanDefinition(name, beanDefinition);
            }
        }
    }
}

该类使用了以下注解:

  • @Configuration:用于定义一个配置类,可用于替换 Spring 中的 xml 配置文件;
  • @Bean:被 @Configuration 注解的类内部,可以包含有一个或多个被 @Bean 注解的方法,用于构建一个 Bean,并添加到 Spring 容器中;该注解与 spring 配置文件中 等价,方法名与 的 id 或 name 属性等价,方法返回值与 class 属性等价;

除了 @Configuration 和 @Bean 注解外,该类还使用 5 个 @Conditional 衍生注解:

  • @ConditionalOnClass({ServletRequest.class}):判断当前项目是否存在 ServletRequest 这个类,若存在,则该配置类生效。
  • @ConditionalOnWebApplication(type = Type.SERVLET):判断当前应用是否是 Web 应用,如果是的话,当前配置类生效。
  • @ConditionalOnClass(name = {“org.apache.catalina.startup.Tomcat”}):判断是否存在 Tomcat 类,若存在则该方法生效。
  • @ConditionalOnMissingFilterBean({ForwardedHeaderFilter.class}):判断容器中是否有 ForwardedHeaderFilter 这个过滤器,若不存在则该方法生效。
  • @ConditionalOnProperty(value = {“server.forward-headers-strategy”},havingValue = “framework”):判断配置文件中是否存在 server.forward-headers-strategy = framework,若不存在则该方法生效。

ServerProperties

ServletWebServerFactoryAutoConfiguration 类还使用了一个 @EnableConfigurationProperties 注解,通过该注解导入了一个 ServerProperties 类,其部分源码如下。

@ConfigurationProperties(
    prefix = "server",
    ignoreUnknownFields = true
)
public class ServerProperties {
    private Integer port;
    private InetAddress address;
    @NestedConfigurationProperty
    private final ErrorProperties error = new ErrorProperties();
    private ServerProperties.ForwardHeadersStrategy forwardHeadersStrategy;
    private String serverHeader;
    private DataSize maxHttpHeaderSize = DataSize.ofKilobytes(8L);
    private Shutdown shutdown;
    @NestedConfigurationProperty
    private Ssl ssl;
    @NestedConfigurationProperty
    private final Compression compression;
    @NestedConfigurationProperty
    private final Http2 http2;
    private final ServerProperties.Servlet servlet;
    private final ServerProperties.Tomcat tomcat;
    private final ServerProperties.Jetty jetty;
    private final ServerProperties.Netty netty;
    private final ServerProperties.Undertow undertow;
    public ServerProperties() {
        this.shutdown = Shutdown.IMMEDIATE;
        this.compression = new Compression();
        this.http2 = new Http2();
        this.servlet = new ServerProperties.Servlet();
        this.tomcat = new ServerProperties.Tomcat();
        this.jetty = new ServerProperties.Jetty();
        this.netty = new ServerProperties.Netty();
        this.undertow = new ServerProperties.Undertow();
    }
    ....
}

我们看到,ServletWebServerFactoryAutoConfiguration 使用了一个 @EnableConfigurationProperties 注解,而 ServerProperties 类上则使用了一个 @ConfigurationProperties 注解。这其实是 Spring Boot 自动配置机制中的通用用法。

Spring Boot 中为我们提供了大量的自动配置类 XxxAutoConfiguration 以及 XxxProperties,每个自动配置类 XxxAutoConfiguration 都使用了 @EnableConfigurationProperties 注解,而每个 XxxProperties 上都使用 @ConfigurationProperties 注解。

@ConfigurationProperties 注解的作用,是将这个类的所有属性与配置文件中相关的配置进行绑定,以便于获取或修改配置,但是 @ConfigurationProperties 功能是由容器提供的,被它注解的类必须是容器中的一个组件,否则该功能就无法使用。而 @EnableConfigurationProperties 注解的作用正是将指定的类以组件的形式注入到 IOC 容器中,并开启其 @ConfigurationProperties 功能。因此,@ConfigurationProperties + @EnableConfigurationProperties 组合使用,便可以为 XxxProperties 类实现配置绑定功能。

自动配置类 XxxAutoConfiguration 负责使用 XxxProperties 中属性进行自动配置,而 XxxProperties 则负责将自动配置属性与配置文件的相关配置进行绑定,以便于用户通过配置文件修改默认的自动配置。也就是说,真正“限制”我们可以在配置文件中配置哪些属性的类就是这些 XxxxProperties 类,它与配置文件中定义的 prefix 关键字开头的一组属性是唯一对应的。

注意:XxxAutoConfiguration 与 XxxProperties 并不是一一对应的,大多数情况都是多对多的关系,即一个 XxxAutoConfiguration 可以同时使用多个 XxxProperties 中的属性,一个 XxxProperties 类中属性也可以被多个 XxxAutoConfiguration 使用。

Spring Boot统一日志框架

在项目开发中,日志十分的重要,不管是记录运行情况还是定位线上问题,都离不开对日志的分析。在 Java 领域里存在着多种日志框架,如 JCL、SLF4J、Jboss-logging、jUL、log4j、log4j2、logback 等等。

日志框架的选择

市面上常见的日志框架有很多,它们可以被分为两类:日志门面(日志抽象层)和日志实现,如下表。

日志分类 描述 举例
日志门面(日志抽象层) 为 Java 日志访问提供一套标准和规范的 API 框架,其主要意义在于提供接口。 JCL(Jakarta Commons Logging)、SLF4j(Simple Logging Facade for Java)、jboss-logging
日志实现 日志门面的具体的实现 Log4j、JUL(java.util.logging)、Log4j2、Logback

通常情况下,日志由一个日志门面与一个日志实现组合搭建而成,Spring Boot 选用 SLF4J + Logback 的组合来搭建日志系统。

SLF4J 是目前市面上最流行的日志门面,使用 Slf4j 可以很灵活的使用占位符进行参数占位,简化代码,拥有更好的可读性。

Logback 是 Slf4j 的原生实现框架,它与 Log4j 出自一个人之手,但拥有比 log4j 更多的优点、特性和更做强的性能,现在基本都用来代替 log4j 成为主流。

SLF4J 的使用

在项目开发中,记录日志时不应该直接调用日志实现层的方法,而应该调用日志门面(日志抽象层)的方法。

在使用 SLF4J 记录日志时,我们需要在应用中导入 SLF4J 及日志实现,并在记录日志时调用 SLF4J 的方法,例如:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
    public static void main(String[] args) {
        Logger logger = LoggerFactory.getLogger(HelloWorld.class);
       //调用 sl4j 的 info() 方法,而非调用 logback 的方法
        logger.info("Hello World");
    }
}

SLF4J 作为一款优秀的日志门面或者日志抽象层,它可以与各种日志实现框架组合使用,以达到记录日志的目的,如下图(参考自 SLF4J 官方)。

从 SLF4J 官方给出的方案可以看出:

  • Logback 作为 Slf4j 的原生实现框架,当应用使用 SLF4J+Logback 的组合记录日志时,只需要引入 SLF4J 和 Logback 的 Jar 包即可;
  • Log4j 虽然与 Logback 出自同一个人之手,但是 Log4j 出现要早于 SLF4J,因而 Log4j 没有直接实现 SLF4J,当应用使用 SLF4J+Log4j 的组合记录日志时,不但需要引入 SLF4J 和 Log4j 的 Jar 包,还必须引入它们之间的适配层(Adaptation layer)slf4j-log4j12.jar,该适配层可谓“上有老下有小”,它既要实现 SLF4J 的方法,还有调用 Log4j 的方法,以达到承上启下的作用;
  • 当应用使用 SLF4J+JUL 记录日志时,与 SLF4J+Log4j 一样,不但需要引入 SLF4J 和 JUL 的对应的 Jar 包,还要引入适配层 slf4j-jdk14.jar。

这里我们需要注意一点,每一个日志的实现框架都有自己的配置文件。使用 slf4j 记录日志时,配置文件应该使用日志实现框架(例如 logback、log4j 和 JUL 等等)自己本身的配置文件。

统一日志框架(通用)

通常一个完整的应用下会依赖于多种不同的框架,而且它们记录日志使用的日志框架也不尽相同,例如,Spring Boot(slf4j+logback),Spring(commons-logging)、Hibernate(jboss-logging)等等。那么如何统一日志框架的使用呢?

对此,SLF4J 官方也给出了相应的解决方案,如下图。

从上图中可以看出,统一日志框架一共需要以下 3 步 :

  1. 排除应用中的原来的日志框架;
  2. 引入替换包替换被排除的日志框架;
  3. 导入 SLF4J 实现。

SLF4J 官方给出的统一日志框架的方案是“狸猫换太子”,即使用一个替换包来替换原来的日志框架,例如 log4j-over-slf4j 替换 Log4j(Commons Logging API)、jul-to-slf4j.jar 替换 JUL(java.util.logging API)等等。

替换包内包含被替换的日志框架中的所有类,这样就可以保证应用不会报错,但替换包内部实际使用的是 SLF4J API,以达到统一日主框架的目的。

统一日志框架(Spring Boot)

我们在使用 Spring Boot 时,同样可能用到其他的框架,例如 Mybatis、Spring MVC、 Hibernate 等等,这些框架的底层都有自己的日志框架,此时我们也需要对日志框架进行统一。

我们知道,统一日志框架的使用一共分为 3 步,Soring Boot 作为一款优秀的开箱即用的框架,已经为用户完成了其中 2 步:引入替换包和导入 SLF4J 实现。

Spring Boot 的核心启动器 spring-boot-starter 引入了 spring-boot-starter-logging,使用 IDEA 查看其依赖关系,如下图。

从上图可知,spring-boot-starter-logging 的 Maven 依赖不但引入了 logback-classic (包含了日志框架 SLF4J 的实现),还引入了 log4j-to-slf4j(log4j 的替换包),jul-to-slf4j (JUL 的替换包),即 Spring Boot 已经为我们完成了统一日志框架的 3 个步骤中的 2 步。

SpringBoot 底层使用 slf4j+logback 的方式记录日志,当我们引入了依赖了其他日志框架的第三方框架(例如 Hibernate)时,只需要把这个框架所依赖的日志框架排除,即可实现日志框架的统一,示例代码如下。

<dependency>
    <groupId>org.apache.activemq</groupId>
    <artifactId>activemq-console</artifactId>
    <version>${activemq.version}</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Spring Boot日志配置及输出

默认配置

Spring Boot 默认使用 SLF4J+Logback 记录日志,并提供了默认配置,即使我们不进行任何额外配,也可以使用 SLF4J+Logback 进行日志输出。

常见的日志配置包括日志级别、日志的输入出格式等内容。

日志级别

日志的输出都是分级别的,当一条日志信息的级别大于或等于配置文件的级别时,就对这条日志进行记录。

常见的日志级别如下(优先级依次升高)。

序号 日志级别 说明
1 trace 追踪,指明程序运行轨迹。
2 debug 调试,实际应用中一般将其作为最低级别,而 trace 则很少使用。
3 info 输出重要的信息,使用较多。
4 warn 警告,使用较多。
5 error 错误信息,使用较多。

输出格式

我们可以通过以下常用日志参数对日志的输出格式进行修改,如下表。

序号 输出格式 说明
1 %d{yyyy-MM-dd HH:mm:ss, SSS} 日志生产时间,输出到毫秒的时间
2 %-5level 输出日志级别,-5 表示左对齐并且固定输出 5 个字符,如果不足在右边补 0
3 %logger 或 %c logger 的名称
4 %thread 或 %t 输出当前线程名称
5 %p 日志输出格式
6 %message 或 %msg 或 %m 日志内容,即 logger.info(“message”)
7 %n 换行符
8 %class 或 %C 输出 Java 类名
9 %file 或 %F 输出文件名
10 %L 输出错误行号
11 %method 或 %M 输出方法名
12 %l 输出语句所在的行数, 包括类名、方法名、文件名、行数
13 hostName 本地机器名
14 hostAddress 本地 ip 地址

示例 1

下面我们通过一个实例,来查看 Spring Boot 提供了哪些默认日志配置。

  1. 在 Spring Boot 中编写 Java 测试类,代码如下。
package net.biancheng.www;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootLoggingApplicationTests {
    Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 测试日志输出
     * SLF4J 日志级别从小到大trace>debug>info>warn>error
     */
    @Test
    void logTest() {
        //日志级别 由低到高
        logger.trace("trace 级别日志");
        logger.debug("debug 级别日志");
        logger.info("info 级别日志");
        logger.warn("warn 级别日志");
        logger.error("error 级别日志");
    }
}
  1. 执行该测试,控制台输出如下图。

通过控制台输出结果可知,Spring Boot 日志默认级别为 info,日志输出内容默认包含以下元素:

  • 时间日期
  • 日志级别
  • 进程 ID
  • 分隔符:—
  • 线程名:方括号括起来(可能会截断控制台输出)
  • Logger 名称
  • 日志内容

修改默认日志配置

我们可以根据自身的需求,通过全局配置文件(application.properties/yml)修改 Spring Boot 日志级别和显示格式等默认配置。

在 application.properties 中,修改 Spring Boot 日志的默认配置,代码如下。

#日志级别
logging.level.net.biancheng.www=trace
#使用相对路径的方式设置日志输出的位置(项目根目录目录\my-log\mylog\spring.log)
#logging.file.path=my-log/myLog
#绝对路径方式将日志文件输出到 【项目所在磁盘根目录\springboot\logging\my\spring.log】
logging.file.path=/spring-boot/logging
#控制台日志输出格式
logging.pattern.console=%d{yyyy-MM-dd hh:mm:ss} [%thread] %-5level %logger{50} - %msg%n
#日志文件输出格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} === - %msg%n

执行测试代码,执行结果如下。

从上图 可以看到,控制台中日志的输出格式与 application.properties 中的 logging.pattern.console 配置一致。

查看本地日志文件 spring.log,该文件日志输出内容如下图。

从上图 可以看到,本地日志文件中的日志输出格式与 application.properties 中 logging.pattern.file 配置一致。

自定义日志配置

在 Spring Boot 的配置文件 application.porperties/yml 中,可以对日志的一些默认配置进行修改,但这种方式只能修改个别的日志配置,想要修改更多的配置或者使用更高级的功能,则需要通过日志实现框架自己的配置文件进行配置。

Spring 官方提供了各个日志实现框架所需的配置文件,用户只要将指定的配置文件放置到项目的类路径下即可。

日志框架 配置文件
Logback logback-spring.xml、logback-spring.groovy、logback.xml、logback.groovy
Log4j2 log4j2-spring.xml、log4j2.xml
JUL (Java Util Logging) logging.properties

从上表可以看出,日志框架的配置文件基本上被分为 2 类:

  • 普通日志配置文件,即不带 srping 标识的配置文件,例如 logback.xml;
  • 带有 spring 表示的日志配置文件,例如 logback-spring.xml。
    这两种日志配置文件在使用时大不相同,下面我们就对它们分别进行介绍。

普通日志配置文件

我们将 logback.xml、log4j2.xml 等不带 spring 标识的普通日志配置文件,放在项目的类路径下后,这些配置文件会跳过 Spring Boot,直接被日志框架加载。通过这些配置文件,我们就可以达到自定义日志配置的目的。

示例

  1. 将 logback.xml 加入到 Spring Boot 项目的类路径下(resources 目录下),该配置文件配置内容如下。
<?xml version="1.0" encoding="UTF-8"?>
<!--
scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true。
scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒当scan为true时,此属性生效。默认的时间间隔为1分钟。
debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。
-->
<configuration scan="false" scanPeriod="60 seconds" debug="false">
    <!-- 定义日志的根目录 -->
    <property name="LOG_HOME" value="/app/log"/>
    <!-- 定义日志文件名称 -->
    <property name="appName" value="bianchengbang-spring-boot-logging"></property>
    <!-- ch.qos.logback.core.ConsoleAppender 表示控制台输出 -->
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <!--
        日志输出格式:
   %d表示日期时间,
   %thread表示线程名,
   %-5level:级别从左显示5个字符宽度
   %logger{50} 表示logger名字最长50个字符,否则按照句点分割。
   %msg:日志消息,
   %n是换行符
        -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread]**************** %-5level %logger{50} - %msg%n</pattern>
        </layout>
    </appender>
    <!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
    <appender name="appLogAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!-- 指定日志文件的名称 -->
        <file>${LOG_HOME}/${appName}.log</file>
        <!--
        当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名
        TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动。
        -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--
            滚动时产生的文件的存放位置及文件名称 %d{yyyy-MM-dd}:按天进行日志滚动
            %i:当文件大小超过maxFileSize时,按照i进行文件滚动
            -->
            <fileNamePattern>${LOG_HOME}/${appName}-%d{yyyy-MM-dd}-%i.log</fileNamePattern>
            <!--
            可选节点,控制保留的归档文件的最大数量,超出数量就删除旧文件。假设设置每天滚动,
            且maxHistory是365,则只保存最近365天的文件,删除之前的旧文件。注意,删除旧文件是,
            那些为了归档而创建的目录也会被删除。
            -->
            <MaxHistory>365</MaxHistory>
            <!--
            当日志文件超过maxFileSize指定的大小是,根据上面提到的%i进行日志文件滚动 注意此处配置SizeBasedTriggeringPolicy是无法实现按文件大小进行滚动的,必须配置timeBasedFileNamingAndTriggeringPolicy
            -->
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <!-- 日志输出格式: -->
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [ %thread ] ------------------ [ %-5level ] [ %logger{50} : %line ] -
                %msg%n
            </pattern>
        </layout>
    </appender>
    <!--
  logger主要用于存放日志对象,也可以定义日志类型、级别
  name:表示匹配的logger类型前缀,也就是包的前半部分
  level:要记录的日志级别,包括 TRACE < DEBUG < INFO < WARN < ERROR
  additivity:作用在于children-logger是否使用 rootLogger配置的appender进行输出,
  false:表示只用当前logger的appender-ref,true:
  表示当前logger的appender-ref和rootLogger的appender-ref都有效
    -->
    <!-- hibernate logger -->
    <logger name="net.biancheng.www" level="debug"/>
    <!-- Spring framework logger -->
    <logger name="org.springframework" level="debug" additivity="false"></logger>
    <!--
    root与logger是父子关系,没有特别定义则默认为root,任何一个类只会和一个logger对应,
    要么是定义的logger,要么是root,判断的关键在于找到这个logger,然后判断这个logger的appender和level。
    -->
    <root level="info">
        <appender-ref ref="stdout"/>
        <appender-ref ref="appLogAppender"/>
    </root>
</configuration> 
  1. 启动该项目并启动测试程序,结果如下。
  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::                (v2.5.0)
2021-05-24 14:51:11 [main]**************** INFO  n.biancheng.www.SpringBootLoggingApplicationTests - Starting SpringBootLoggingApplicationTests using Java 1.8.0_131 on LAPTOP-C67MRMAG with PID 20080 (started by 79330 in D:\eclipse workSpace4\spring-boot-logging)
2021-05-24 14:51:11 [main]**************** DEBUG n.biancheng.www.SpringBootLoggingApplicationTests - Running with Spring Boot v2.5.0, Spring v5.3.7
2021-05-24 14:51:11 [main]**************** INFO  n.biancheng.www.SpringBootLoggingApplicationTests - The following profiles are active: dev
2021-05-24 14:51:13 [main]**************** INFO  n.biancheng.www.SpringBootLoggingApplicationTests - Started SpringBootLoggingApplicationTests in 2.058 seconds (JVM running for 3.217)
2021-05-24 14:51:13 [main]**************** DEBUG n.biancheng.www.SpringBootLoggingApplicationTests - debug 级别日志
2021-05-24 14:51:13 [main]**************** INFO  n.biancheng.www.SpringBootLoggingApplicationTests - info 级别日志
2021-05-24 14:51:13 [main]**************** WARN  n.biancheng.www.SpringBootLoggingApplicationTests - warn 级别日志
2021-05-24 14:51:13 [main]**************** ERROR n.biancheng.www.SpringBootLoggingApplicationTests - error 级别日志

带有 spring 标识的日志配置文件

Spring Boot 推荐用户使用 logback-spring.xml、log4j2-spring.xml 等这种带有 spring 标识的配置文件。这种配置文件被放在项目类路径后,不会直接被日志框架加载,而是由 Spring Boot 对它们进行解析,这样就可以使用 Spring Boot 的高级功能 Profile,实现在不同的环境中使用不同的日志配置。

示例

  1. 将 logback.xml 文件名修改为 logback-spring.xml,并将配置文件中日志输出格式的配置修改为使用 Profile 功能的配置。

  2. 配置内容修改前,日志输出格式配置如下。

<configuration scan="false" scanPeriod="60 seconds" debug="false">
    ......
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
        <layout class="ch.qos.logback.classic.PatternLayout">
            <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread]**************** %-5level %logger{50} - %msg%n</pattern>
        </layout>
    </appender>
    ......
</configuration> 
  1. 修改 logback-spring.xml 的配置内容,通过 Profile 功能实现在不同的环境中使用不同的日志输出格式,配置如下。
<configuration scan="false" scanPeriod="60 seconds" debug="false">
    ......
    <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
       <layout class="ch.qos.logback.classic.PatternLayout">
            <!--开发环境 日志输出格式-->
            <springProfile name="dev">
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%n</pattern>
            </springProfile>
            <!--非开发环境 日志输出格式-->
            <springProfile name="!dev">
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%n</pattern>
            </springProfile>
        </layout>
    </appender>
    ......
</configuration> 
  1. 在 Spring Boot 项目的 application.yml 中,激活开发环境(dev)的 Profile,配置内容如下。
#默认配置
server:
  port: 8080
#切换配置
spring:
  profiles:
    active: dev
---
#开发环境
server:
  port: 8081
spring:
  config:
    activate:
      on-profile: dev
---
#测试环境
server:
  port: 8082
spring:
  config:
    activate:
      on-profile: test
---
#生产环境
server:
  port: 8083
spring:
  config:
    activate:
      on-profile: prod
  1. 启动 Spring Boot 并执行测试代码,控制台输出如下。

  1. 修改 appplication.yml 中的配置,激活测试环境(test)的 Profile,配置如下。
#默认配置
server:
  port: 8080
#切换配置
spring:
  profiles:
    active: test
---
#开发环境
server:
  port: 8081
spring:
  config:
    activate:
      on-profile: dev
---
#测试环境
server:
  port: 8082
spring:
  config:
    activate:
      on-profile: test
---
#生产环境
server:
  port: 8083
spring:
  config:
    activate:
      on-profile: prod
  1. 重启 Spring Boot 并执行测试代码,控制台输出如下。

spring-boot-starter-web(Web启动器)

Spring MVC 是 Spring 提供的一个基于 MVC 设计模式的轻量级 Web 开发框架,其本身就是 Spring 框架的一部分,可以与 Spring 无缝集成,性能方面具有先天的优越性,是当今业界最主流的 Web 开发框架之一。

Spring Boot 是在 Spring 的基础上创建一款开源框架,它提供了 spring-boot-starter-web(Web 场景启动器) 来为 Web 开发予以支持。spring-boot-starter-web 为我们提供了嵌入的 Servlet 容器以及 SpringMVC 的依赖,并为 Spring MVC 提供了大量自动配置,可以适用于大多数 Web 开发场景。

Spring Boot Web 快速开发

Spring Boot 为 Spring MVC 提供了自动配置,并在 Spring MVC 默认功能的基础上添加了以下特性:

  • 引入了 ContentNegotiatingViewResolver 和 BeanNameViewResolver(视图解析器)
  • 对包括 WebJars 在内的静态资源的支持
  • 自动注册 Converter、GenericConverter 和 Formatter (转换器和格式化器)
  • 对 HttpMessageConverters 的支持(Spring MVC 中用于转换 HTTP 请求和响应的消息转换器)
  • 自动注册 MessageCodesResolver(用于定义错误代码生成规则)
  • 支持对静态首页(index.html)的访问
  • 自动使用 ConfigurableWebBindingInitializer

只要我们在 Spring Boot 项目中的 pom.xml 中引入了 spring-boot-starter-web ,即使不进行任何配置,也可以直接使用 Spring MVC 进行 Web 开发。

示例

  1. 创建一个名为 spring-boot-springmvc-demo1 的 Spring Boot 工程,并在其 pom.xml 的dependencies 节点中添加 spring-boot-starter-web 的依赖,代码如下。
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  1. 在 net.biancheng.www 包下创建一个名为 HelloController,代码如下。
package net.biancheng.www.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
        return "www.biancheng.net";
    }
}
  1. 启动 Spring Boot,浏览器访问“http://localhost:8080/hello”,结果如下图。

注意:由于 spring-boot-starter-web 默认替我们引入了核心启动器 spring-boot-starter,因此,当 Spring Boot 项目中的 pom.xml 引入了 spring-boot-starter-web 的依赖后,就无须在引入 spring-boot-starter 核心启动器的依赖了。

Spring Boot静态资源映射

在 Web 应用中会涉及到大量的静态资源,例如 JS、CSS 和 HTML 等。我们知道,Spring MVC 导入静态资源文件时,需要配置静态资源的映射;但在 SpringBoot 中则不再需要进行此项配置,因为 SpringBoot 已经默认完成了这一工作。

Spring Boot 默认为我们提供了 3 种静态资源映射规则:

  • WebJars 映射
  • 默认资源映射
  • 静态首页(欢迎页)映射

WebJars 映射

为了让页面更加美观,让用户有更多更好的体验,Web 应用中通常会使用大量的 JS 和 CSS,例如 jQuery,Backbone.js 和 Bootstrap 等等。通常我们会将这些 Web 前端资源拷贝到 Java Web 项目的 webapp 相应目录下进行管理。但是 Spring Boot 项目是以 JAR 包的形式进行部署的,不存在 webapp 目录,那么 Web 前端资源该如何引入到 Spring Boot 项目中呢?

WebJars 可以完美的解决上面的问题,它可以 Jar 形式为 Web 项目提供资源文件。

WebJars 可以将 Web 前端资源(JS,CSS 等)打成一个个的 Jar 包,然后将这些 Jar 包部署到 Maven 中央仓库中进行统一管理,当 Spring Boot 项目中需要引入 Web 前端资源时,只需要访问 WebJars 官网,找到所需资源的 pom 依赖,将其导入到项目中即可。

所有通过 WebJars 引入的前端资源都存放在当前项目类路径(classpath)下的“/META-INF/resources/webjars/” 目录中。

下图展示如何通过 WebJars 查找 JQuery 的 pom 依赖的过程。

Spring Boot 通过 MVC 的自动配置类 WebMvcAutoConfiguration 为这些 WebJars 前端资源提供了默认映射规则,部分源码如下。

public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (!this.resourceProperties.isAddMappings()) {
        logger.debug("Default resource handling disabled");
    } else {
        //WebJars 映射规则
        this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
        this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
            registration.addResourceLocations(this.resourceProperties.getStaticLocations());
            if (this.servletContext != null) {
                ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
                registration.addResourceLocations(new Resource[]{resource});
            }
        });
    }
}

通过以上源码可知,WebJars 的映射路径为“/webjars/”,即所有访问“/webjars/”的请求,都会去“classpath:/META-INF/resources/webjars/”查找 WebJars 前端资源。

示例 1

  1. 在 Spring Boot 项目 spring-boot-springmvc-demo1 的 pom.xml 中添加以下依赖,将 jquery 引入到该项目中。
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.6.0</version>
</dependency>
  1. Spring Boot 项目中引入的 jquery 的 Jar 包结构如下图。

  1. 启动 Spring Boot,浏览器访问“http://localhost:8080/webjars/jquery/3.6.0/jquery.js”访问 jquery.js,结果如下图。

默认静态资源映射

当访问项目中的任意资源(即“/**”)时,Spring Boot 会默认从以下路径中查找资源文件(优先级依次降低):

  1. classpath:/META-INF/resources/
  2. classpath:/resources/
  3. classpath:/static/
  4. classpath:/public/

这些路径又被称为静态资源文件夹,它们的优先级顺序为:classpath:/META-INF/resources/ > classpath:/resources/ > classpath:/static/ > classpath:/public/ 。

当我们请求某个静态资源(即以“.html”结尾的请求)时,Spring Boot 会先查找优先级高的文件夹,再查找优先级低的文件夹,直到找到指定的静态资源为止。

示例 2

  1. 在 spring-boot-springmvc-demo1 的 src/main/resources 下的 static 目录中创建一个 hello.html,代码如下。
<!DOCTYPE html>
<html lang="en">
<head></head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<body>
<h1>欢迎您来到编程帮(www.biancheng.net)</h1>
</body>
</html>
  1. 启动 Spring Boot,浏览器访问 “http://localhost:8080/hello.html”,结果如下图。

静态首页(欢迎页)映射

静态资源文件夹下的所有 index.html 被称为静态首页或者欢迎页,它们会被被 /** 映射,换句话说就是,当我们访问“/”或者“/index.html”时,都会跳转到静态首页(欢迎页)。

注意,访问静态首页或欢迎页时,其查找顺序也遵循默认静态资源的查找顺序,即先查找优先级高的目录,在查找优先级低的目录,直到找到 index.html 为止。

示例 3

  1. 在 spring-boot-springmvc-demo1 的 src/main/resources 下的 public 目录中创建一个 index.html,代码如下。
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
</body>
</html>
  1. 启动 Spring Boot,使用浏览器访问“http://localhost:8080/”,结果如下图。

Spring Boot定制Spring MVC

Spring Boot 抛弃了传统 xml 配置文件,通过配置类(标注 @Configuration 的类,相当于一个 xml 配置文件)以 JavaBean 形式进行相关配置。

Spring Boot 对 Spring MVC 的自动配置可以满足我们的大部分需求,但是我们也可以通过自定义配置类(标注 @Configuration 的类)并实现 WebMvcConfigurer 接口来定制 Spring MVC 配置,例如拦截器、格式化程序、视图控制器等等。

SpringBoot 1.5 及以前是通过继承 WebMvcConfigurerAdapter 抽象类来定制 Spring MVC 配置的,但在 SpringBoot 2.0 后,WebMvcConfigurerAdapter 抽象类就被弃用了,改为实现 WebMvcConfigurer 接口来定制 Spring MvVC 配置。

WebMvcConfigurer 是一个基于 Java 8 的接口,该接口定义了许多与 Spring MVC 相关的方法,其中大部分方法都是 default 类型的,且都是空实现。因此我们只需要定义一个配置类实现 WebMvcConfigurer 接口,并重写相应的方法便可以定制 Spring MVC 的配置。

方法 说明
default void configurePathMatch(PathMatchConfigurer configurer) {} HandlerMappings 路径的匹配规则。
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {} 内容协商策略(一个请求路径返回多种数据格式)。
default void configureAsyncSupport(AsyncSupportConfigurer configurer) {} 处理异步请求。
default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {} 这个接口可以实现静态文件可以像 Servlet 一样被访问。
default void addFormatters(FormatterRegistry registry) {} 添加格式化器或者转化器。
default void addInterceptors(InterceptorRegistry registry) {} 添加 Spring MVC 生命周期拦截器,对请求进行拦截处理。
default void addResourceHandlers(ResourceHandlerRegistry registry) {} 添加或修改静态资源(例如图片,js,css 等)映射; Spring Boot 默认设置的静态资源文件夹就是通过重写该方法设置的。
default void addCorsMappings(CorsRegistry registry) {} 处理跨域请求。
default void addViewControllers(ViewControllerRegistry registry) {} 主要用于实现无业务逻辑跳转,例如主页跳转,简单的请求重定向,错误页跳转等
default void configureViewResolvers(ViewResolverRegistry registry) {} 配置视图解析器,将 Controller 返回的字符串(视图名称),转换为具体的视图进行渲染。
default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {} 添加解析器以支持自定义控制器方法参数类型,实现该方法不会覆盖用于解析处理程序方法参数的内置支持; 要自定义内置的参数解析支持, 同样可以通过 RequestMappingHandlerAdapter 直接配置 RequestMappingHandlerAdapter 。
default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {} 添加处理程序来支持自定义控制器方法返回值类型。使用此选项不会覆盖处理返回值的内置支持; 要自定义处理返回值的内置支持,请直接配置 RequestMappingHandlerAdapter。
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {} 用于配置默认的消息转换器(转换 HTTP 请求和响应)。
default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {} 直接添加消息转换器,会关闭默认的消息转换器列表; 实现该方法即可在不关闭默认转换器的起提下,新增一个自定义转换器。
default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {} 配置异常解析器。
default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {} 扩展或修改默认的异常解析器列表。

在 Spring Boot 项目中,我们可以通过以下 2 中形式定制 Spring MVC:

  • 扩展 Spring MVC
  • 全面接管 Spring MVC

下面,我们分别对这两种定制 Spring MVC 的形式进行介绍。

扩展 Spring MVC

如果 Spring Boot 对 Spring MVC 的自动配置不能满足我们的需要,我们还可以通过自定义一个 WebMvcConfigurer 类型(实现 WebMvcConfigurer 接口)的配置类(标注 @Configuration,但不标注 @EnableWebMvc 注解的类),来扩展 Spring MVC。这样不但能够保留 Spring Boot 对 Spring MVC 的自动配置,享受 Spring Boot 自动配置带来的便利,还能额外增加自定义的 Spring MVC 配置。

示例 1

  1. 创建一个名为 spring-boot-adminex 的 Spring Boot 项目,并将后台管理系统 AdminEx 中的 css、fonts、images 和 js 目录及其中的静态资源,移动到该项目的 src/main/resources/static 下,目录结构如下图。

  1. 在 net.biancheng.www.config 包下,创建一个名为 MyMvcConfig 的配置类并实现 WebMvcConfigurer 接口,重写 addViewControllers() 方法,代码如下。
package net.biancheng.www.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
//实现 WebMvcConfigurer 接口可以来扩展 SpringMVC 的功能
//@EnableWebMvc   不要接管SpringMVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //当访问 “/” 或 “/index.html” 时,都直接跳转到登陆页面
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index.html").setViewName("login");
    }
}
  1. 在 net.biancheng.www.controller 下创建一个名为 IndexController 的 Controller,代码如下。
package net.biancheng.www.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
    /**
     * 跳转到登陆页面
     *
     * @return
     */
    @GetMapping(value = {"/login"})
    public String loginPage() {
        //跳转到登录页 login.html
        return "login";
    }
}
  1. 将 AdminEx 中的 login.html(登录页)移动到 src/main/resources/templates 下,结构如下图。

  1. 启动 Spring Boot,您会发现“http://localhost:8080/login”、“http://localhost:8080/”“http://localhost:8080/index.html”3 个 URL 都能跳转到登陆页 login.html,结果如下图。

全面接管 Spring MVC

在一些特殊情况下,我们可能需要抛弃 Spring Boot 对 Spring MVC 的全部自动配置,完全接管 Spring MVC。此时我们可以自定义一个 WebMvcConfigurer 类型(实现 WebMvcConfigurer 接口)的配置类,并在该类上标注 @EnableWebMvc 注解,来实现完全接管 Spring MVC。

注意:完全接管 Spring MVC 后,Spring Boot 对 Spring MVC 的自动配置将全部失效。

示例 2

  1. 在 MyMvcConfig 配置类上标注 @EnableWebMvc,除此之外其他文件都不做任何修改,代码如下。
package net.biancheng.www.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
//实现 WebMvcConfigurer 接口可以来扩展 SpringMVC 的功能
@EnableWebMvc  // 完全接管SpringMVC
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //当访问 “/” 或 “/index.html” 时,都直接跳转到登陆页面
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index.html").setViewName("login");
    }
}
  1. 启动 Spring Boot,在浏览器地址栏输入“http://localhost:8080/”访问登录页,结果如下图。

  1. 浏览器地址栏输入“http://localhost:8080/css/style.css” ,访问 login.html 中引用的 css 样式表,结果如下图。

我们知道,Spring Boot 能够访问位于静态资源文件夹中的静态文件,这是在 Spring Boot 对 Spring MVC 的默认自动配置中定义的,当我们全面接管 Spring MVC 后,Spring Boot 对 Spring MVC 的默认配置都会失效,此时再访问静态资源文件夹中的静态资源就会报 404 错误。

Thymeleaf教程

Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。它与 JSP,Velocity,FreeMaker 等模板引擎类似,也可以轻易地与 Spring MVC 等 Web 框架集成。与其它模板引擎相比,Thymeleaf 最大的特点是,即使不启动 Web 应用,也可以直接在浏览器中打开并正确显示模板页面 。

1. Thymeleaf 简介

Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

Thymeleaf 通过在 html 标签中,增加额外属性来达到“模板+数据”的展示方式,示例代码如下。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text 为 Thymeleaf 属性,用于在展示文本-->
<h1 th:text="迎您来到Thymeleaf">欢迎您访问静态页面 HTML</h1>
</body>
</html>

当直接使用浏览器打开时,浏览器展示结果如下。

欢迎您访问静态页面HTML

当通过 Web 应用程序访问时,浏览器展示结果如下。

迎您来到Thymeleaf

Thymeleaf 的特点

Thymeleaf 模板引擎具有以下特点:

  • 动静结合:Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。
  • 开箱即用:Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
  • 多方言支持:它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。
  • 与 SpringBoot 完美整合:SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。

2. Thymeleaf 语法规则

在使用 Thymeleaf 之前,首先要在页面的 html 标签中声明名称空间,示例代码如下。

xmlns:th="http://www.thymeleaf.org"

在 html 标签中声明此名称空间,可避免编辑器出现 html 验证错误,但这一步并非必须进行的,即使我们不声明该命名空间,也不影响 Thymeleaf 的使用。

Thymeleaf 作为一种模板引擎,它拥有自己的语法规则。Thymeleaf 语法分为以下 2 类:

  • 标准表达式语法
  • th 属性

2.1 标准表达式语法

Thymeleaf 模板引擎支持多种表达式:

  • 变量表达式:${…}
  • 选择变量表达式:*{…}
  • 链接表达式:@{…}
  • 国际化表达式:#{…}
  • 片段引用表达式:~{…}

2.1.1 变量表达式

使用 ${} 包裹的表达式被称为变量表达式,该表达式具有以下功能:

  • 获取对象的属性和方法
  • 使用内置的基本对象
  • 使用内置的工具对象

① 获取对象的属性和方法

使用变量表达式可以获取对象的属性和方法,例如,获取 person 对象的 lastName 属性,表达式形式如下:

${person.lastName}

② 使用内置的基本对象

使用变量表达式还可以使用内置基本对象,获取内置对象的属性,调用内置对象的方法。 Thymeleaf 中常用的内置基本对象如下:

  • #ctx :上下文对象;
  • #vars :上下文变量;
  • #locale:上下文的语言环境;
  • #request:HttpServletRequest 对象(仅在 Web 应用中可用);
  • #response:HttpServletResponse 对象(仅在 Web 应用中可用);
  • #session:HttpSession 对象(仅在 Web 应用中可用);
  • #servletContext:ServletContext 对象(仅在 Web 应用中可用)。

例如,我们通过以下 2 种形式,都可以获取到 session 对象中的 map 属性:

${#session.getAttribute('map')}
${session.map}

③ 使用内置的工具对象

除了能使用内置的基本对象外,变量表达式还可以使用一些内置的工具对象。

  • strings:字符串工具对象,常用方法有:equals、equalsIgnoreCase、length、trim、toUpperCase、toLowerCase、indexOf、substring、replace、startsWith、endsWith,contains 和 containsIgnoreCase 等;
  • numbers:数字工具对象,常用的方法有:formatDecimal 等;
  • bools:布尔工具对象,常用的方法有:isTrue 和 isFalse 等;
  • arrays:数组工具对象,常用的方法有:toArray、length、isEmpty、contains 和 containsAll 等;
  • lists/sets:List/Set 集合工具对象,常用的方法有:toList、size、isEmpty、contains、containsAll 和 sort 等;
  • maps:Map 集合工具对象,常用的方法有:size、isEmpty、containsKey 和 containsValue 等;
  • dates:日期工具对象,常用的方法有:format、year、month、hour 和 createNow 等。

例如,我们可以使用内置工具对象 strings 的 equals 方法,来判断字符串与对象的某个属性是否相等,代码如下。

${#strings.equals('编程帮',name)}

2.1.2 选择变量表达式

选择变量表达式与变量表达式功能基本一致,只是在变量表达式的基础上增加了与 th:object 的配合使用。当使用 th:object 存储一个对象后,我们可以在其后代中使用选择变量表达式({…})获取该对象中的属性,其中,“”即代表该对象。

<div th:object="${session.user}" >
    <p th:text="*{fisrtName}">firstname</p>
</div>

th:object 用于存储一个临时变量,该变量只在该标签及其后代中有效,在后面的内容“th 属性”中我详细介绍。

2.1.3 链接表达式

不管是静态资源的引用,还是 form 表单的请求,凡是链接都可以用链接表达式 (@{…})。 链接表达式的形式结构如下: 无参请求:@{/xxx} 有参请求:@{/xxx(k1=v1,k2=v2)} 例如使用链接表达式引入 css 样式表,代码如下。

<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">

2.1.4 国际化表达式

消息表达式一般用于国际化的场景。结构如下。

th:text="#{msg}"

注意:此处了解即可,我们会在后面的章节中详细介绍。

2.1.5 片段引用表达式

片段引用表达式用于在模板页面中引用其他的模板片段,该表达式支持以下 2 中语法结构:

  • 推荐:~{templatename::fragmentname}
  • 支持:~{templatename::#id}

以上语法结构说明如下:

  • templatename:模版名,Thymeleaf 会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。
  • fragmentname:片段名,Thymeleaf 通过 th:fragment 声明定义代码块,即:th:fragment=”fragmentname”
  • id:HTML 的 id 选择器,使用时要在前面加上 # 号,不支持 class 选择器。

2.2 th 属性

Thymeleaf 还提供了大量的 th 属性,这些属性可以直接在 HTML 标签中使用,其中常用 th 属性及其示例如下表。

属性 描述 示例
th:id 替换 HTML 的 id 属性 <input id="html-id" th:id="thymeleaf-id" />
th:text 文本替换,转义特殊字符 <h1 th:text="hello,bianchengbang" >hello</h1>
th:utext 文本替换,不转义特殊字符 <div th:utext="<h1>欢迎来到编程帮!</h1>" >欢迎你</div>
th:object 在父标签选择对象,子标签使用 *{…} 选择表达式选取值。 没有选择对象,那子标签使用选择表达式和 ${…} 变量表达式是一样的效果。 同时即使选择了对象,子标签仍然可以使用变量表达式。 <div th:object="${session.user}" > <p th:text="*{fisrtName}">firstname</p></div>
th:value 替换 value 属性 <input th:value = "${user.name}" />
th:with 局部变量赋值运算 <div th:with="isEvens = ${prodStat.count}%2 == 0" th:text="${isEvens}"></div>
th:style 设置样式 <div th:style="'color:#F00; font-weight:bold'">编程帮 www.biancheng.net</div>
th:onclick 点击事件 <td th:onclick = "'getInfo()'"></td>
th:each 遍历,支持 Iterable、Map、数组等。 <table> <tr th:each="m:${session.map}"> <td th:text="${m.getKey()}"></td> <td th:text="${m.getValue()}"></td> </tr></table>
th:if 根据条件判断是否需要展示此标签 <a th:if ="${userId == collect.userId}">
th:unless 和 th:if 判断相反,满足条件时不显示 <div th:unless="${m.getKey()=='name'}" ></div>
th:switch 与 Java 的 switch case语句类似 通常与 th:case 配合使用,根据不同的条件展示不同的内容 <div th:switch="${name}"> <span th:case="a">编程帮</span> <span th:case="b">www.biancheng.net</span></div>
th:fragment 模板布局,类似 JSP 的 tag,用来定义一段被引用或包含的模板片段 <footer th:fragment="footer">插入的内容</footer>
th:insert 布局标签; 将使用 th:fragment 属性指定的模板片段(包含标签)插入到当前标签中。 <div th:insert="commons/bar::footer"></div>
th:replace 布局标签; 使用 th:fragment 属性指定的模板片段(包含标签)替换当前整个标签。 <div th:replace="commons/bar::footer"></div>
th:selected select 选择框选中 <select> <option>---</option> <option th:selected="${name=='a'}"> 编程帮 </option> <option th:selected="${name=='b'}"> www.biancheng.net </option></select>
th:src 替换 HTML 中的 src 属性 <img th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" />
th:inline 内联属性; 该属性有 text,none,javascript 三种取值, 在 <script> 标签中使用时,js 代码中可以获取到后台传递页面的对象。 <script type="text/javascript" th:inline="javascript"> var name = /*[[${name}]]*/ 'bianchengbang'; alert(name)</script>
th:action 替换表单提交地址 <form th:action="@{/user/login}" th:method="post"></form>

3. Thymeleaf 公共页面抽取

在 Web 项目中,通常会存在一些公共页面片段(重复代码),例如头部导航栏、侧边菜单栏和公共的 js css 等。我们一般会把这些公共页面片段抽取出来,存放在一个独立的页面中,然后再由其他页面根据需要进行引用,这样可以消除代码重复,使页面更加简洁。

3.1 抽取公共页面

Thymeleaf 作为一种优雅且高度可维护的模板引擎,同样支持公共页面的抽取和引用。我们可以将公共页面片段抽取出来,存放到一个独立的页面中,并使用 Thymeleaf 提供的 th:fragment 属性为这些抽取出来的公共页面片段命名。

示例 1

将公共页面片段抽取出来,存放在 commons.html 中,代码如下。

<div th:fragment="fragment-name" id="fragment-id">
    <span>公共页面片段</span>
</div>

3.2 引用公共页面

在 Thymeleaf 中,我们可以使用以下 3 个属性,将公共页面片段引入到当前页面中。

  • th:insert:将代码块片段整个插入到使用了 th:insert 属性的 HTML 标签中;
  • th:replace:将代码块片段整个替换使用了 th:replace 属性的 HTML 标签中;
  • th:include:将代码块片段包含的内容插入到使用了 th:include 属性的 HTML 标签中。

使用上 3 个属性引入页面片段,都可以通过以下 2 种方式实现。

  • ~{templatename::selector}:模板名::选择器
  • ~{templatename::fragmentname}:模板名::片段名

通常情况下,{} 可以省略,其行内写法为 [[{…}]] 或 [({…})],其中 [[{…}]] 会转义特殊字符,[(~{…})] 则不会转义特殊字符。

示例 2

  1. 在页面 fragment.html 中引入 commons.html 中声明的页面片段,可以通过以下方式实现。
<!--th:insert 片段名引入-->
<div th:insert="commons::fragment-name"></div>
<!--th:insert id 选择器引入-->
<div th:insert="commons::#fragment-id"></div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div th:replace="commons::fragment-name"></div>
<!--th:replace id 选择器引入-->
<div th:replace="commons::#fragment-id"></div>
------------------------------------------------
<!--th:include 片段名引入-->
<div th:include="commons::fragment-name"></div>
<!--th:include id 选择器引入-->
<div th:include="commons::#fragment-id"></div>
  1. 启动 Spring Boot,使用浏览器访问 fragment.html,查看源码,结果如下。
<!--th:insert 片段名引入-->
<div>
    <div id="fragment-id">
        <span>公共页面片段</span>
    </div>
</div>
<!--th:insert id 选择器引入-->
<div>
    <div id="fragment-id">
        <span>公共页面片段</span>
    </div>
</div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div id="fragment-id">
    <span>公共页面片段</span>
</div>
<!--th:replace id 选择器引入-->
<div id="fragment-id">
    <span>公共页面片段</span>
</div>
------------------------------------------------
<!--th:include 片段名引入-->
<div>
    <span>公共页面片段</span>
</div>
<!--th:include id 选择器引入-->
<div>
    <span>公共页面片段</span>
</div>

3.3 传递参数

Thymeleaf 在抽取和引入公共页面片段时,还可以进行参数传递,大致步骤如下:

  1. 传入参数;
  2. 使用参数。

3.3.1 传入参数

引用公共页面片段时,我们可以通过以下 2 种方式,将参数传入到被引用的页面片段中:

  • 模板名::选择器名或片段名(参数1=参数值1,参数2=参数值2)
  • 模板名::选择器名或片段名(参数值1,参数值2)

注:

  • 若传入参数较少时,一般采用第二种方式,直接将参数值传入页面片段中;
  • 若参数较多时,建议使用第一种方式,明确指定参数名和参数值,。

示例代码如下:

<!--th:insert 片段名引入-->
<div th:insert="commons::fragment-name(var1='insert-name',var2='insert-name2')"></div>
<!--th:insert id 选择器引入-->
<div th:insert="commons::#fragment-id(var1='insert-id',var2='insert-id2')"></div>
------------------------------------------------
<!--th:replace 片段名引入-->
<div th:replace="commons::fragment-name(var1='replace-name',var2='replace-name2')"></div>
<!--th:replace id 选择器引入-->
<div th:replace="commons::#fragment-id(var1='replace-id',var2='replace-id2')"></div>
------------------------------------------------
<!--th:include 片段名引入-->
<div th:include="commons::fragment-name(var1='include-name',var2='include-name2')"></div>
<!--th:include id 选择器引入-->
<div th:include="commons::#fragment-id(var1='include-id',var2='include-id2')"></div>

3.3.2 使用参数

在声明页面片段时,我们可以在片段中声明并使用这些参数,例如:

<!--使用 var1 和 var2 声明传入的参数,并在该片段中直接使用这些参数 -->
<div th:fragment="fragment-name(var1,var2)" id="fragment-id">
    <p th:text="'参数1:'+${var1} + '-------------------参数2:' + ${var2}">...</p>
</div>

启动 Spring Boot,使用浏览器访问 fragment.html,结果如下图。

Spring Boot整合Thymeleaf

Spring Boot 推荐使用 Thymeleaf 作为其模板引擎。SpringBoot 为 Thymeleaf 提供了一系列默认配置,项目中一但导入了 Thymeleaf 的依赖,相对应的自动配置 (ThymeleafAutoConfiguration 或 FreeMarkerAutoConfiguration) 就会自动生效,因此 Thymeleaf 可以与 Spring Boot 完美整合 。

Spring Boot 整合 Thymeleaf 模板引擎,需要以下步骤:

  1. 引入 Starter 依赖
  2. 创建模板文件,并放在在指定目录下

引入依赖

Spring Boot 整合 Thymeleaf 的第一步,就是在项目的 pom.xml 中添加 Thymeleaf 的 Starter 依赖,代码如下。

<!--Thymeleaf 启动器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

创建模板文件

Spring Boot 通过 ThymeleafAutoConfiguration 自动配置类对 Thymeleaf 提供了一整套的自动化配置方案,该自动配置类的部分源码如下。

@Configuration(
    proxyBeanMethods = false
)
@EnableConfigurationProperties({ThymeleafProperties.class})
@ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class})
@AutoConfigureAfter({WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class})
public class ThymeleafAutoConfiguration {
}

ThymeleafAutoConfiguration 使用 @EnableConfigurationProperties 注解导入了 ThymeleafProperties 类,该类包含了与 Thymeleaf 相关的自动配置属性,其部分源码如下。

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
    private boolean cache;
...
}

ThymeleafProperties 通过 @ConfigurationProperties 注解将配置文件(application.properties/yml) 中前缀为 spring.thymeleaf 的配置和这个类中的属性绑定。

在 ThymeleafProperties 中还提供了以下静态变量:

  • DEFAULT_ENCODING:默认编码格式
  • DEFAULT_PREFIX:视图解析器的前缀
  • DEFAULT_SUFFIX:视图解析器的后缀

根据以上配置属性可知,Thymeleaf 模板的默认位置在 resources/templates 目录下,默认的后缀是 html,即只要将 HTML 页面放在“classpath:/templates/”下,Thymeleaf 就能自动进行渲染。

与 Spring Boot 其他自定义配置一样,我们可以在 application.properties/yml 中修改以 spring.thymeleaf 开始的属性,以实现修改 Spring Boot 对 Thymeleaf 的自动配置的目的。

示例

  1. 创建一个名为 hello.html 的页面,并将该页面放在项目类路径(resources)下的 templates 目录中,hello.html 代码如下。
<!DOCTYPE html>
<!--导入thymeleaf的名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text 为 Thymeleaf 属性,用于获取指定属性的值-->
<h1 th:text="'欢迎来到'+${name}"></h1>
</body>
</html>
  1. 新建一个控制类 HelloController,并通过参数 map 传递数据到前台页面中,代码如下。
package net.biancheng.www.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public String hello(Map<String, Object> map) {
        //通过 map 向前台页面传递数据
        map.put("name", "编程帮(www.biancheng.net)");
        return "hello";
    }
}
  1. 启动 Spring Boot,使用浏览器访问“http://localhost:8080/hello”,结果如下图。

Spring Boot国际化

国际化(Internationalization 简称 I18n,其中“I”和“n”分别为首末字符,18 则为中间的字符数)是指软件开发时应该具备支持多种语言和地区的功能。换句话说就是,开发的软件需要能同时应对不同国家和地区的用户访问,并根据用户地区和语言习惯,提供相应的、符合用具阅读习惯的页面和数据,例如,为中国用户提供汉语界面显示,为美国用户提供提供英语界面显示。

在 Spring 项目中实现国际化,通常需要以下 3 步:

  1. 编写国际化资源(配置)文件;
  2. 使用 ResourceBundleMessageSource 管理国际化资源文件;
  3. 在页面获取国际化内容。

1. 编写国际化资源文件

在 Spring Boot 的类路径下创建国际化资源文件,文件名格式为:基本名_语言代码_国家或地区代码,例如 login_en_US.properties、login_zh_CN.properties。

以 spring-boot-springmvc-demo1为例,在 src/main/resources 下创建一个 i18n 的目录,并在该目录中按照国际化资源文件命名格式分别创建以下三个文件,

  • login.properties:无语言设置时生效
  • login_en_US.properties :英语时生效
  • login_zh_CN.properties:中文时生效

以上国际化资源文件创建完成后,IDEA 会自动识别它们,并转换成如下的模式:

打开任意一个国际化资源文件,并切换为 Resource Bundle 模式,然后点击“+”号,创建所需的国际化属性,如下图。

2. 使用 ResourceBundleMessageSource 管理国际化资源文件

Spring Boot 已经对 ResourceBundleMessageSource 提供了默认的自动配置。

Spring Boot 通过 MessageSourceAutoConfiguration 对 ResourceBundleMessageSource 提供了默认配置,其部分源码如下。

@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(name = AbstractApplicationContext.MESSAGE_SOURCE_BEAN_NAME, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration.ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {
    private static final Resource[] NO_RESOURCES = {};
    // 将 MessageSourceProperties 以组件的形式添加到容器中
    // MessageSourceProperties 下的每个属性都与以 spring.messages 开头的属性对应
    @Bean
    @ConfigurationProperties(prefix = "spring.messages")
    public MessageSourceProperties messageSourceProperties() {
        return new MessageSourceProperties();
    }
    //Spring Boot 会从容器中获取 MessageSourceProperties
    // 读取国际化资源文件的 basename(基本名)、encoding(编码)等信息
    // 并封装到 ResourceBundleMessageSource 中
    @Bean
    public MessageSource messageSource(MessageSourceProperties properties) {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        //读取国际化资源文件的 basename (基本名),并封装到 ResourceBundleMessageSource 中
        if (StringUtils.hasText(properties.getBasename())) {
            messageSource.setBasenames(StringUtils
                    .commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(properties.getBasename())));
        }
        //读取国际化资源文件的 encoding (编码),并封装到 ResourceBundleMessageSource 中
        if (properties.getEncoding() != null) {
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }
        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        Duration cacheDuration = properties.getCacheDuration();
        if (cacheDuration != null) {
            messageSource.setCacheMillis(cacheDuration.toMillis());
        }
        messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
        messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
        return messageSource;
    }
    ...
}

从以上源码可知:

  • Spring Boot 将 MessageSourceProperties 以组件的形式添加到容器中;
  • MessageSourceProperties 的属性与配置文件中以“spring.messages”开头的配置进行了绑定;
  • Spring Boot 从容器中获取 MessageSourceProperties 组件,并从中读取国际化资源文件的 basename(文件基本名)、encoding(编码)等信息,将它们封装到 ResourceBundleMessageSource 中;
  • Spring Boot 将 ResourceBundleMessageSource 以组件的形式添加到容器中,进而实现对国际化资源文件的管理。

查看 MessageSourceProperties 类,其代码如下。

public class MessageSourceProperties {
    private String basename = "messages";
    private Charset encoding;
    @DurationUnit(ChronoUnit.SECONDS)
    private Duration cacheDuration;
    private boolean fallbackToSystemLocale;
    private boolean alwaysUseMessageFormat;
    private boolean useCodeAsDefaultMessage;
    public MessageSourceProperties() {
        this.encoding = StandardCharsets.UTF_8;
        this.fallbackToSystemLocale = true;
        this.alwaysUseMessageFormat = false;
        this.useCodeAsDefaultMessage = false;
    }
    ...
}

通过以上代码,我们可以得到以下 3 点信息:

  • MessageSourceProperties 为 basename、encoding 等属性提供了默认值;
  • basename 表示国际化资源文件的基本名,其默认取值为“message”,即 Spring Boot 默认会获取类路径下的 message.properties 以及 message_XXX.properties 作为国际化资源文件;
  • 在 application.porperties/yml 等配置文件中,使用配置参数“spring.messages.basename”即可重新指定国际化资源文件的基本名。

通过以上源码分析可知,Spring Boot 已经对国际化资源文件的管理提供了默认自动配置,我们这里只需要在 Spring Boot 全局配置文件中,使用配置参数“spring.messages.basename”指定我们自定义的国际资源文件的基本名即可,代码如下(当指定多个资源文件时,用逗号分隔)。

spring.messages.basename=i18n.login

3. 获取国际化内容

由于页面使用的是 Tymeleaf 模板引擎,因此我们可以通过表达式 #{…} 获取国际化内容。

以 spring-boot-adminex 为例,在 login.html 中获取国际化内容,代码如下。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="ThemeBucket">
    <link rel="shortcut icon" href="#" type="image/png">
    <title>Login</title>
    <!--将js css 等静态资源的引用修改为 绝对路径-->
    <link href="css/style.css" th:href="@{/css/style.css}" rel="stylesheet">
    <link href="css/style-responsive.css" th:href="@{/css/style-responsive.css}" rel="stylesheet">
    <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js" th:src="@{/js/html5shiv.js}"></script>
    <script src="js/respond.min.js" th:src="@{/js/respond.min.js}"></script>
    <![endif]-->
</head>
<body class="login-body">
<div class="container">
    <form class="form-signin" th:action="@{/user/login}" method="post">
        <div class="form-signin-heading text-center">
            <h1 class="sign-title" th:text="#{login.btn}">Sign In</h1>
            <img src="/images/login-logo.png" th:src="@{/images/login-logo.png}" alt=""/>
        </div>
        <div class="login-wrap">
            <p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>
            <input type="text" class="form-control" name="username" placeholder="User ID" autofocus
                   th:placeholder="#{login.username}"/>
            <input type="password" class="form-control" name="password" placeholder="Password"
                   th:placeholder="#{login.password}"/>
            <label class="checkbox">
                <input type="checkbox" value="remember-me" th:text="#{login.remember}">
                <span class="pull-right">
                    <a data-toggle="modal" href="#myModal" th:text="#{login.forgot}"> </a>
                </span>
            </label>
            <button class="btn btn-lg btn-login btn-block" type="submit">
                <i class="fa fa-check"></i>
            </button>
            <div class="registration">
                <!--Thymeleaf 行内写法-->
                [[#{login.not-a-member}]]
                <a class="" href="/registration.html" th:href="@{/registration.html}">
                    [[#{login.signup}]]
                </a>
                <!--thymeleaf 模板引擎的参数用()代替 ?-->
                <br/>
                <a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>|
                <a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
            </div>
        </div>
        <!-- Modal -->
        <div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="myModal"
             class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title">Forgot Password ?</h4>
                    </div>
                    <div class="modal-body">
                        <p>Enter your e-mail address below to reset your password.</p>
                        <input type="text" name="email" placeholder="Email" autocomplete="off"
                               class="form-control placeholder-no-fix">
                    </div>
                    <div class="modal-footer">
                        <button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
                        <button class="btn btn-primary" type="button">Submit</button>
                    </div>
                </div>
            </div>
        </div>
        <!-- modal -->
    </form>
</div>
<!-- Placed js at the end of the document so the pages load faster -->
<!-- Placed js at the end of the document so the pages load faster -->
<script src="js/jquery-1.10.2.min.js" th:src="@{/js/jquery-1.10.2.min.js}"></script>
<script src="js/bootstrap.min.js" th:src="@{/js/bootstrap.min.js}"></script>
<script src="js/modernizr.min.js" th:src="@{/js/modernizr.min.js}"></script>
</body>
</html>

将浏览器语言切换为英文,再次访问登陆页,结果如下图。

手动切换语言

如下图所示,在登陆页(login.html)最下方有两个切换语言的链接,想要通过点击它们来切换进行国际化的语言,该怎么做呢?

区域信息解析器自动配置

我们知道,Spring MVC 进行国际化时有 2 个十分重要的对象:

  • Locale:区域信息对象
  • LocaleResolver:区域信息解析器,容器中的组件,负责获取区域信息对象

我们可以通过以上两个对象对区域信息的切换,以达到切换语言的目的。

Spring Boot 在 WebMvcAutoConfiguration 中为区域信息解析器(LocaleResolver)进行了自动配置,源码如下。

    @Bean
    @ConditionalOnMissingBean(name = DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME)
    @SuppressWarnings("deprecation")
    public LocaleResolver localeResolver() {
        if (this.webProperties.getLocaleResolver() == WebProperties.LocaleResolver.FIXED) {
            return new FixedLocaleResolver(this.webProperties.getLocale());
        }
        if (this.mvcProperties.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
            return new FixedLocaleResolver(this.mvcProperties.getLocale());
        }
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        Locale locale = (this.webProperties.getLocale() != null) ? this.webProperties.getLocale()
                : this.mvcProperties.getLocale();
        localeResolver.setDefaultLocale(locale);
        return localeResolver;
    }

从以上源码可知:

  • 该方法默认向容器中添加了一个区域信息解析器(LocaleResolver)组件,它会根据请求头中携带的“Accept-Language”参数,获取相应区域信息(Locale)对象。
  • 该方法上使用了 @ConditionalOnMissingBean 注解,其参数 name 的取值为 localeResolver(与该方法注入到容器中的组件名称一致),该注解的含义为:当容器中不存在名称为 localResolver 组件时,该方法才会生效。换句话说,当我们手动向容器中添加一个名为“localeResolver”的组件时,Spring Boot 自动配置的区域信息解析器会失效,而我们定义的区域信息解析器则会生效。

手动切换语言

  1. 修改 login.html 切换语言链接,在请求中携带国际化区域信息,代码如下。
<!--thymeleaf 模板引擎的参数用()代替 ?-->
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>|
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>
  1. 在 net.biancheng.www 下创建一个 component 包,并在该包中创建一个区域信息解析器 MyLocalResolver,代码如下。
package net.biancheng.www.componet;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
//自定义区域信息解析器
public class MyLocalResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        //获取请求中参数
        String l = request.getParameter("l");
        //获取默认的区域信息解析器
        Locale locale = Locale.getDefault();
        //根据请求中的参数重新构造区域信息对象
        if (StringUtils.hasText(l)) {
            String[] s = l.split("_");
            locale = new Locale(s[0], s[1]);
        }
        return locale;
    }
    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
    }
}
  1. 在 net.biancheng.www.config 的 MyMvcConfig 中添加以下方法,将自定义的区域信息解析器以组件的形式添加到容器中,代码如下。
//将自定义的区域信息解析器以组件的形式添加到容器中
@Bean
public LocaleResolver localeResolver(){
    return new MyLocalResolver();
}
  1. 启动 Spring Boot,访问登录页 login.html,结果如下图。

  1. 点击页面最下方的“English”链接,将语言切换到英语,结果如下图。

Spring Boot拦截器

我们对拦截器并不陌生,无论是 Struts 2 还是 Spring MVC 中都提供了拦截器功能,它可以根据 URL 对请求进行拦截,主要应用于登陆校验、权限验证、乱码解决、性能监控和异常处理等功能上。Spring Boot 同样提供了拦截器功能。

在 Spring Boot 项目中,使用拦截器功能通常需要以下 3 步:

  1. 定义拦截器;
  2. 注册拦截器;
  3. 指定拦截规则(如果是拦截所有,静态资源也会被拦截)。

定义拦截器

在 Spring Boot 中定义拦截器十分的简单,只需要创建一个拦截器类,并实现 HandlerInterceptor 接口即可。

HandlerInterceptor 接口中定义以下 3 个方法,如下表。

返回值类型 方法声明 描述
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) 该方法在控制器处理请求方法前执行,其返回值表示是否中断后续操作,返回 true 表示继续向下执行,返回 false 表示中断后续操作。
void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) 该方法在控制器处理请求方法调用之后、解析视图之前执行,可以通过此方法对请求域中的模型和视图做进一步修改。
void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 该方法在视图渲染结束后执行,可以通过此方法实现资源清理、记录日志信息等工作。

示例1

以 spring-boot-adminex 项目为例,在 net.biancheng.www.componet 中创建一个名为 LoginInterceptor 的拦截器类,对登陆进行拦截,代码如下。

package net.biancheng.www.componet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 目标方法执行前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            //未登录,返回登陆页
            request.setAttribute("msg", "您没有权限进行此操作,请先登陆!");
            request.getRequestDispatcher("/index.html").forward(request, response);
            return false;
        } else {
            //放行
            return true;
        }
    }
    /**
     * 目标方法执行后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle执行{}", modelAndView);
    }
    /**
     * 页面渲染后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion执行异常{}", ex);
    }
}

注册拦截器

创建一个实现了 WebMvcConfigurer 接口的配置类(使用了 @Configuration 注解的类),重写 addInterceptors() 方法,并在该方法中调用 registry.addInterceptor() 方法将自定义的拦截器注册到容器中。

示例 2

在配置类 MyMvcConfig 中,添加以下方法注册拦截器,代码如下。

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    ......
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor());
    }
}

指定拦截规则

在使用 registry.addInterceptor() 方法将拦截器注册到容器中后,我们便可以继续指定拦截器的拦截规则了,代码如下。

@Slf4j
@Configuration
public class MyConfig implements WebMvcConfigurer {
    ......
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info("注册拦截器");
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**") //拦截所有请求,包括静态资源文件
                .excludePathPatterns("/", "/login", "/index.html", "/user/login", "/css/**", "/images/**", "/js/**", "/fonts/**"); //放行登录页,登陆操作,静态资源
    }
}

在指定拦截器拦截规则时,调用了两个方法,这两个方法的说明如下:

  • addPathPatterns:该方法用于指定拦截路径,例如拦截路径为“/**”,表示拦截所有请求,包括对静态资源的请求。
  • excludePathPatterns:该方法用于排除拦截路径,即指定不需要被拦截器拦截的请求。

至此,拦截器的基本功能已经完成,接下来,我们先实现 spring-boot-adminex 的登陆功能,为验证登陆拦截做准备。

实现登陆功能

  1. 将 AdminEx 模板中的 main.html 移动到 src/main/resources/templates 中,结构如下图。

  1. 在 net.bianheng.www.controller 中创建一个 LoginController, 并在其中添加处理登陆请求的方法 doLogin(),代码如下。
package net.biancheng.www.controller;
import lombok.extern.slf4j.Slf4j;
import net.biancheng.www.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Slf4j
@Controller
public class LoginController {
    @RequestMapping("/user/login")
    public String doLogin(User user, Map<String, Object> map, HttpSession session) {
        if (user != null && StringUtils.hasText(user.getUsername()) && "123456".equals(user.getPassword())) {
            session.setAttribute("loginUser", user);
            log.info("登陆成功,用户名:" + user.getUsername());
            //防止重复提交使用重定向
            return "redirect:/main.html";
        } else {
            map.put("msg", "用户名或密码错误");
            log.error("登陆失败");
            return "login";
        }
    }
/*
    @RequestMapping("/main.html")
    public String mainPage(){
        return "main";
    }*/
}
  1. 在配置类 MyMvcConfig 中添加视图映射,代码如下。
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //当访问 “/” 或 “/index.html” 时,都直接跳转到登陆页面
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/index.html").setViewName("login");
        //添加视图映射 main.html 指向  dashboard.html
        registry.addViewController("/main.html").setViewName("main");
    }
    ......
}
  1. 在 login.html 适当位置添加以下代码,显示错误信息。
<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

验证登陆及登陆拦截功能

  1. 启动 Spring Boot,在未登录的情况下,直接通过“http://localhost:8080/main.html”访问主页,结果如下图。

  1. 在登陆页用户名和密码输入框内分别输入 “admin”和“admin123”,点击下方的登陆按钮,结果如下图。

  1. 在登陆页用户名和密码输入框内分别输入 “admin”和“123456”,点击下方的登陆按钮,结果如下图。

Spring Boot默认异常处理

在日常的 Web 开发中,会经常遇到大大小小的异常,此时往往需要一个统一的异常处理机制,来保证客户端能接收较为友好的提示。Spring Boot 同样提供了一套默认的异常处理机制

Spring Boot 默认异常处理机制

Spring Boot 提供了一套默认的异常处理机制,一旦程序中出现了异常,Spring Boot 会自动识别客户端的类型(浏览器客户端或机器客户端),并根据客户端的不同,以不同的形式展示异常信息。

  1. 对于浏览器客户端而言,Spring Boot 会响应一个“ whitelabel”错误视图,以 HTML 格式呈现错误信息,如图 1;

  1. 对于机器客户端而言,Spring Boot 将生成 JSON 响应,来展示异常消息。
{
    "timestamp": "2021-07-12T07:05:29.885+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/m1ain.html"
}

Spring Boot 异常处理自动配置原理

Spring Boot 通过配置类 ErrorMvcAutoConfiguration 对异常处理提供了自动配置,该配置类向容器中注入了以下 4 个组件。

  • ErrorPageCustomizer:该组件会在在系统发生异常后,默认将请求转发到“/error”上。

  • BasicErrorController:处理默认的“/error”请求。

  • DefaultErrorViewResolver:默认的错误视图解析器,将异常信息解析到相应的错误视图上。

  • DefaultErrorAttributes:用于页面上共享异常信息。

下面,我们依次对这四个组件进行详细的介绍。

ErrorPageCustomizer

ErrorMvcAutoConfiguration 向容器中注入了一个名为 ErrorPageCustomizer 的组件,它主要用于定制错误页面的响应规则。

@Bean
public ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath dispatcherServletPath) {
    return new ErrorPageCustomizer(this.serverProperties, dispatcherServletPath);
}

ErrorPageCustomizer 通过 registerErrorPages() 方法来注册错误页面的响应规则。当系统中发生异常后,ErrorPageCustomizer 组件会自动生效,并将请求转发到 “/error”上,交给 BasicErrorController 进行处理,其部分代码如下。

@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
    //将请求转发到 /errror(this.properties.getError().getPath())上
    ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
    // 注册错误页面
    errorPageRegistry.addErrorPages(errorPage);
}

BasicErrorController

ErrorMvcAutoConfiguration 还向容器中注入了一个错误控制器组件 BasicErrorController,代码如下。

@Bean
@ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
public BasicErrorController basicErrorController(ErrorAttributes errorAttributes,
                                                 ObjectProvider<ErrorViewResolver> errorViewResolvers) {
    return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
            errorViewResolvers.orderedStream().collect(Collectors.toList()));
}

BasicErrorController 的定义如下。

//BasicErrorController 用于处理 “/error” 请求
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
    ......
    /**
     * 该方法用于处理浏览器客户端的请求发生的异常
     * 生成 html 页面来展示异常信息
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        //获取错误状态码
        HttpStatus status = getStatus(request);
        //getErrorAttributes 根据错误信息来封装一些 model 数据,用于页面显示
        Map<String, Object> model = Collections
                .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        //为响应对象设置错误状态码
        response.setStatus(status.value());
        //调用 resolveErrorView() 方法,使用错误视图解析器生成 ModelAndView 对象(包含错误页面地址和页面内容)
        ModelAndView modelAndView = resolveErrorView(request, response, status, model);
        return (modelAndView != null) ? modelAndView : new ModelAndView("error", model);
    }
    /**
     * 该方法用于处理机器客户端的请求发生的错误
     * 产生 JSON 格式的数据展示错误信息
     * @param request
     * @return
     */
    @RequestMapping
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        return new ResponseEntity<>(body, status);
    }
    ......
}

Spring Boot 通过 BasicErrorController 进行统一的错误处理(例如默认的“/error”请求)。Spring Boot 会自动识别发出请求的客户端的类型(浏览器客户端或机器客户端),并根据客户端类型,将请求分别交给 errorHtml() 和 error() 方法进行处理。

返回值类型 方法声明 客户端类型 错误信息返类型
ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) 浏览器客户端 text/html(错误页面)
ResponseEntity<Map<String, Object>> error(HttpServletRequest request) 机器客户端(例如安卓、IOS、Postman 等等) JSON

换句话说,当使用浏览器访问出现异常时,会进入 BasicErrorController 控制器中的 errorHtml() 方法进行处理,当使用安卓、IOS、Postman 等机器客户端访问出现异常时,就进入error() 方法处理。

在 errorHtml() 方法中会调用父类(AbstractErrorController)的 resolveErrorView() 方法,代码如下。

protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status,
                                        Map<String, Object> model) {
    //获取容器中的所有的错误视图解析器来处理该异常信息
    for (ErrorViewResolver resolver : this.errorViewResolvers) {
        //调用错误视图解析器的 resolveErrorView 解析到错误视图页面
        ModelAndView modelAndView = resolver.resolveErrorView(request, status, model);
        if (modelAndView != null) {
            return modelAndView;
        }
    }
    return null;
}

从上述源码可以看出,在响应页面的时候,会在父类的 resolveErrorView 方法中获取容器中所有的 ErrorViewResolver 对象(错误视图解析器,包括 DefaultErrorViewResolver 在内),一起来解析异常信息。

DefaultErrorViewResolver

ErrorMvcAutoConfiguration 还向容器中注入了一个默认的错误视图解析器组件 DefaultErrorViewResolver,代码如下。

@Bean
@ConditionalOnBean(DispatcherServlet.class)
@ConditionalOnMissingBean(ErrorViewResolver.class)
DefaultErrorViewResolver conventionErrorViewResolver() {
    return new DefaultErrorViewResolver(this.applicationContext, this.resources);
}

当发出请求的客户端为浏览器时,Spring Boot 会获取容器中所有的 ErrorViewResolver 对象(错误视图解析器),并分别调用它们的 resolveErrorView() 方法对异常信息进行解析,其中自然也包括 DefaultErrorViewResolver(默认错误信息解析器)。

DefaultErrorViewResolver 的部分代码如下。

public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered {
    private static final Map<HttpStatus.Series, String> SERIES_VIEWS;
    static {
        Map<HttpStatus.Series, String> views = new EnumMap<>(HttpStatus.Series.class);
        views.put(Series.CLIENT_ERROR, "4xx");
        views.put(Series.SERVER_ERROR, "5xx");
        SERIES_VIEWS = Collections.unmodifiableMap(views);
    }
    ......
    @Override
    public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
        //尝试以错误状态码作为错误页面名进行解析
        ModelAndView modelAndView = resolve(String.valueOf(status.value()), model);
        if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
            //尝试以 4xx 或 5xx 作为错误页面页面进行解析
            modelAndView = resolve(SERIES_VIEWS.get(status.series()), model);
        }
        return modelAndView;
    }
    private ModelAndView resolve(String viewName, Map<String, Object> model) {
        //错误模板页面,例如 error/404、error/4xx、error/500、error/5xx
        String errorViewName = "error/" + viewName;
        //当模板引擎可以解析这些模板页面时,就用模板引擎解析
        TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName,
                this.applicationContext);
        if (provider != null) {
            //在模板能够解析到模板页面的情况下,返回 errorViewName 指定的视图
            return new ModelAndView(errorViewName, model);
        }
        //若模板引擎不能解析,则去静态资源文件夹下查找 errorViewName 对应的页面
        return resolveResource(errorViewName, model);
    }
    private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
        //遍历所有静态资源文件夹
        for (String location : this.resources.getStaticLocations()) {
            try {
                Resource resource = this.applicationContext.getResource(location);
                //静态资源文件夹下的错误页面,例如error/404.html、error/4xx.html、error/500.html、error/5xx.html
                resource = resource.createRelative(viewName + ".html");
                //若静态资源文件夹下存在以上错误页面,则直接返回
                if (resource.exists()) {
                    return new ModelAndView(new DefaultErrorViewResolver.HtmlResourceView(resource), model);
                }
            } catch (Exception ex) {
            }
        }
        return null;
    }
    ......
}

DefaultErrorViewResolver 解析异常信息的步骤如下:

  1. 根据错误状态码(例如 404、500、400 等),生成一个错误视图 error/status,例如 error/404、error/500、error/400。
  2. 尝试使用模板引擎解析 error/status 视图,即尝试从 classpath 类路径下的 templates 目录下,查找 error/status.html,例如 error/404.html、error/500.html、error/400.html。
  3. 若模板引擎能够解析到 error/status 视图,则将视图和数据封装成 ModelAndView 返回并结束整个解析流程,否则跳转到第 4 步。
  4. 依次从各个静态资源文件夹中查找 error/status.html,若在静态文件夹中找到了该错误页面,则返回并结束整个解析流程,否则跳转到第 5 步。
  5. 将错误状态码(例如 404、500、400 等)转换为 4xx 或 5xx,然后重复前 4 个步骤,若解析成功则返回并结束整个解析流程,否则跳转第 6 步。
  6. 处理默认的 “/error ”请求,使用 Spring Boot 默认的错误页面(Whitelabel Error Page)。

DefaultErrorAttributes

ErrorMvcAutoConfiguration 还向容器中注入了一个组件默认错误属性处理工具 DefaultErrorAttributes,代码如下。

@Bean
@ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
public DefaultErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes();
}

DefaultErrorAttributes 是 Spring Boot 的默认错误属性处理工具,它可以从请求中获取异常或错误信息,并将其封装为一个 Map 对象返回,其部分代码如下。

public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered {
    ......
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errorAttributes = getErrorAttributes(webRequest, options.isIncluded(Include.STACK_TRACE));
        if (!options.isIncluded(Include.EXCEPTION)) {
            errorAttributes.remove("exception");
        }
        if (!options.isIncluded(Include.STACK_TRACE)) {
            errorAttributes.remove("trace");
        }
        if (!options.isIncluded(Include.MESSAGE) && errorAttributes.get("message") != null) {
            errorAttributes.remove("message");
        }
        if (!options.isIncluded(Include.BINDING_ERRORS)) {
            errorAttributes.remove("errors");
        }
        return errorAttributes;
    }
    private Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        errorAttributes.put("timestamp", new Date());
        addStatus(errorAttributes, webRequest);
        addErrorDetails(errorAttributes, webRequest, includeStackTrace);
        addPath(errorAttributes, webRequest);
        return errorAttributes;
    }
    ......
}

在 Spring Boot 默认的 Error 控制器(BasicErrorController)处理错误时,会调用 DefaultErrorAttributes 的 getErrorAttributes() 方法获取错误或异常信息,并封装成 model 数据(Map 对象),返回到页面或 JSON 数据中。该 model 数据主要包含以下属性:

  • timestamp:时间戳;
  • status:错误状态码
  • error:错误的提示
  • exception:导致请求处理失败的异常对象
  • message:错误/异常消息
  • trace: 错误/异常栈信息
  • path:错误/异常抛出时所请求的URL路径

所有通过 DefaultErrorAttributes 封装到 model 数据中的属性,都可以直接在页面或 JSON 中获取。

Spring Boot全局异常处理

Spring Boot 提供的默认异常处理机制却并不一定适合我们实际的业务场景,因此,我们通常会根据自身的需要对 Spring Boot 全局异常进行统一定制,例如定制错误页面,定制错误数据等。

定制错误页面

我们可以通过以下 3 种方式定制 Spring Boot 错误页面:

  • 自定义 error.html
  • 自定义动态错误页面
  • 自定义静态错误页面

自定义 error.html

我们可以直接在模板引擎文件夹(/resources/templates)下创建 error.html ,覆盖 Spring Boot 默认的错误视图页面(Whitelabel Error Page)。

示例 1

  1. 在 spring-boot-adminex 的模板引擎文件夹(classpath:/resources/templates)下,创建一个 error.html,代码如下。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>自定义 error.html</title>
</head>
<body>
<h1>自定义 error.html</h1>
<p>status:<span th:text="${status}"></span></p>
<p>error:<span th:text="${error}"></span></p>
<p>timestamp:<span th:text="${timestamp}"></span></p>
<p>message:<span th:text="${message}"></span></p>
<p>path:<span th:text="${path}"></span></p>
</body>
</html>
  1. 启动 Spring Boot,在完成登陆跳转到主页后,使用浏览器地访问“http://localhost:8080/111”,结果如下图。

由图 1 可以看出,Spring Boot 使用了我们自定义的 error.html 覆盖了默认的错误视图页面(Whitelabel Error Page)。

自定义动态错误页面

如果 Sprng Boot 项目使用了模板引擎,当程序发生异常时,Spring Boot 的默认错误视图解析器(DefaultErrorViewResolver)就会解析模板引擎文件夹(resources/templates/)下 error 目录中的错误视图页面。

精确匹配

我们可以根据错误状态码(例如 404、500、400 等等)的不同,分别创建不同的动态错误页面(例如 404.html、500.html、400.html 等等),并将它们存放在模板引擎文件夹下的 error 目录中。当发生异常时,Spring Boot 会根据其错误状态码精确匹配到对应的错误页面上。

示例 2

  1. 在 spring-boot-adminex 的模板引擎文件夹下 error 目录中,创建一个名为 404.html 的错误页面,代码如下。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>自定义动态错误页面 404.html</h1>
<p>status:<span th:text="${status}"></span></p>
<p>error:<span th:text="${error}"></span></p>
<p>timestamp:<span th:text="${timestamp}"></span></p>
<p>message:<span th:text="${message}"></span></p>
<p>path:<span th:text="${path}"></span></p>
</body>
</html>
  1. 启动 Spring Boot,在完成登陆跳转到主页后,在浏览器地址栏输入“http://localhost:8080/111”,结果如下图。

模糊匹配

我们还可以使用 4xx.html 和 5xx.html 作为动态错误页面的文件名,并将它们存放在模板引擎文件夹下的 error 目录中,来模糊匹配对应类型的所有错误,例如 404、400 等错误状态码以“4”开头的所有异常,都会解析到动态错误页面 4xx.html 上。

示例 3

在 spring-boot-adminex 的模板引擎文件夹下 error 目录中,创建一个名为 4xx.html 的错误页面,代码如下。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>自定义动态错误页面 4xx.html</h1>
<p>status:<span th:text="${status}"></span></p>
<p>error:<span th:text="${error}"></span></p>
<p>timestamp:<span th:text="${timestamp}"></span></p>
<p>message:<span th:text="${message}"></span></p>
<p>path:<span th:text="${path}"></span></p>
</body>
</html>
  1. 启动 Spring Boot,在完成登陆跳转到主页后,使用浏览器访问“http://localhost:8080/111”,结果如下图。

自定义静态错误页面

若 Sprng Boot 项目没有使用模板引擎,当程序发生异常时,Spring Boot 的默认错误视图解析器(DefaultErrorViewResolver)则会解析静态资源文件夹下 error 目录中的静态错误页面。

精确匹配

我们可以根据错误状态码(例如 404、500、400 等等)的不同,分别创建不同的静态错误页面(例如 404.html、500.html、400.html 等等),并将它们存放在静态资源文件夹下的 error 目录中。当发生异常时,Spring Boot 会根据错误状态码精确匹配到对应的错误页面上。

示例 4

  1. 在 spring-boot-adminex 的静态资源文件夹 src/recources/static 下的 error 目录中,创建一个名为 404.html 的静态错误页面,代码如下。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>自定义静态错误页面 404.html</h1>
<p>status:<span th:text="${status}"></span></p>
<p>error:<span th:text="${error}"></span></p>
<p>timestamp:<span th:text="${timestamp}"></span></p>
<p>message:<span th:text="${message}"></span></p>
<p>path:<span th:text="${path}"></span></p>
</body>
</html>
  1. 启动 Spring Boot,在完成登陆跳转到主页后,使用浏览器访问“http://localhost:8080/111”,结果如下图。

由于该错误页为静态页面,无法识别 Thymeleaf 表达式,因此无法展示与错误相关的错误信息。

模糊匹配

我们还可以使用 4xx.html 和 5xx.html 作为静态错误页面的文件名,并将它们存放在静态资源文件夹下的 error 目录中,来模糊匹配对应类型的所有错误,例如 404、400 等错误状态码以“4”开头的所有错误,都会解析到静态错误页面 4xx.html 上。

示例 3

在 spring-boot-adminex 的模板引擎文件夹下的 error 目录中,创建一个名为 4xx.html 的错误页面,代码如下。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<h1>自定义静态错误页面 4xx.html</h1>
<p>status:<span th:text="${status}"></span></p>
<p>error:<span th:text="${error}"></span></p>
<p>timestamp:<span th:text="${timestamp}"></span></p>
<p>message:<span th:text="${message}"></span></p>
<p>path:<span th:text="${path}"></span></p>
</body>
</html>
  1. 启动 Spring Boot,在完成登陆跳转到主页后,使用浏览器访问“http://localhost:8080/111”,结果如下图。

错误页面优先级

以上 5 种方式均可以定制 Spring Boot 错误页面,且它们的优先级顺序为:自定义动态错误页面(精确匹配)>自定义静态错误页面(精确匹配)>自定义动态错误页面(模糊匹配)>自定义静态错误页面(模糊匹配)>自定义 error.html。

当遇到错误时,Spring Boot 会按照优先级由高到低,依次查找解析错误页,一旦找到可用的错误页面,则直接返回客户端展示。

定制错误数据

我们知道,Spring Boot 提供了一套默认的异常处理机制,其主要流程如下:

  1. 发生异常时,将请求转发到“/error”,交由 BasicErrorController(Spring Boot 默认的 Error 控制器) 进行处理;
  2. BasicErrorController 根据客户端的不同,自动适配返回的响应形式,浏览器客户端返回错误页面,机器客户端返回 JSON 数据。
  3. BasicErrorController 处理异常时,会调用 DefaultErrorAttributes(默认的错误属性处理工具) 的 getErrorAttributes() 方法获取错误数据。

我们还可以定制 Spring Boot 的错误数据,具体步骤如下。

  1. 自定义异常处理类,将请求转发到 “/error”,交由 Spring Boot 底层(BasicErrorController)进行处理,自动适配浏览器客户端和机器客户端。
  2. 通过继承 DefaultErrorAttributes 来定义一个错误属性处理工具,并在原来的基础上添加自定义的错误数据。

1. 自定义异常处理类

被 @ControllerAdvice 注解的类可以用来实现全局异常处理,这是 Spring MVC 中提供的功能,在 Spring Boot 中可以直接使用。

1)在 net.biancheng.net.exception 包内,创建一个名为 UserNotExistException 的异常类,代码如下。

package net.biancheng.www.exception;
/**
* 自定义异常
*/
public class UserNotExistException extends RuntimeException {
    public UserNotExistException() {
        super("用户不存在!");
    }
}

2)在 IndexController 添加以下方法,触发 UserNotExistException 异常,代码如下。

@Controller
public class IndexController {
    ......
    @GetMapping(value = {"/testException"})
    public String testException(String user) {
        if ("user".equals(user)) {
            throw new UserNotExistException();
        }
        //跳转到登录页 login.html
        return "login";
    }
}

3)在 net.biancheng.www.controller 中,创建一个名为 MyExceptionHandler 异常处理类,代码如下。

package net.biancheng.www.controller;
import net.biancheng.www.exception.UserNotExistException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        //向 request 对象传入错误状态码
        request.setAttribute("javax.servlet.error.status_code",500);
        //根据当前处理的异常,自定义的错误数据
        map.put("code", "user.notexist");
        map.put("message", e.getMessage());
        //将自定的错误数据传入 request 域中
        request.setAttribute("ext",map);
        return "forward:/error";
    }
}

2. 自定义错误属性处理工具

1)在 net.biancheng.www.componet 包内,创建一个错误属性处理工具类 MyErrorAttributes(继承 DefaultErrorAttributes ),通过该类我们便可以添加自定义的错误数据,代码如下。

package net.biancheng.www.componet;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import java.util.Map;
//向容器中添加自定义的储物属性处理工具
@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);
        //添加自定义的错误数据
        errorAttributes.put("company", "www.biancheng.net");
        //获取 MyExceptionHandler 传入 request 域中的错误数据
        Map ext = (Map) webRequest.getAttribute("ext", 0);
        errorAttributes.put("ext", ext);
        return errorAttributes;
    }
}

2)在 templates/error 目录下,创建动态错误页面 5xx.html,代码如下。

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>自定义 error.html</title>
</head>
<body>
<p>status:<span th:text="${status}"></span></p>
<p>error:<span th:text="${error}"></span></p>
<p>timestamp:<span th:text="${timestamp}"></span></p>
<p>message:<span th:text="${message}"></span></p>
<p>path:<span th:text="${path}"></span></p>
<!--取出定制的错误信息-->
<h3>以下为定制错误数据:</h3>
<p>company:<span th:text="${company}"></span></p>
<p>code:<span th:text="${ext.code}"></span></p>
<p>path:<span th:text="${ext.message}"></span></p>
</body>
</html>

3)启动 Spring Boot,访问“http://localhost:8080/testException?user=user”,结果如下图。

注意:为了避免拦截器干扰,建议先将拦截器屏蔽掉。

Spring Boot注册Web原生组件(Servlet、Filter、Listener)

由于 Spring Boot 默认以 Jar 包方式部署的,默认没有 web.xml,因此无法再像以前一样通过 web.xml 配置来使用 Servlet 、Filter、Listener,但 Spring Boot 提供了 2 种方式来注册这些 Web 原生组件。

  • 通过组件扫描注册

  • 使用 RegistrationBean 注册

通过组件扫描注册

Servlet 3.0 提供了以下 3 个注解:

  • @WebServlet:用于声明一个 Servlet;
  • @WebFilter:用于声明一个 Filter;
  • @WebListener:用于声明一个 Listener。

这些注解可直接标注在对应组件上,它们与在 web.xml 中的配置意义相同。每个注解都具有与 web.xml 对应的属性,可直接配置,省去了配置 web.xml 的繁琐。

想要在 SpringBoot 中注册这些原生 Web 组件,可以使用 @ServletComponentScan 注解实现,该注解可以扫描标记 @WebServlet、@WebFilter 和 @WebListener 三个注解的组件类,并将它们注册到容器中。

注意:@ServletComponentScan 注解只能标记在启动类或配置类上。

示例

  1. 使用 @WebServlet 注解声明一个自定义的 Servlet,代码如下。
package net.biancheng.www.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
//使用 @WebServlet 注解声明一个 Servlet
@WebServlet(name = "myServlet", urlPatterns = "/myServlet")
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write("Spring Boot Servlet");
        writer.close();
    }
}
  1. 使用 @WebFilter 注解声明一个自定义的 Filter,代码如下。
package net.biancheng.www.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//使用 @WebFilter注解声明一个自定义的 Filter
@WebFilter(urlPatterns = ("/myServlet"))
public class MyFiler implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFiler 初始化");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("MyFiler doFilter");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
        System.out.println("MyFiler 销毁");
    }
}
  1. 使用 @WebListener 注解声明一个自定义的 Listener,代码如下。
package net.biancheng.www.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
//使用 @WebListener 注解声明一个自定义的 Listener
@WebListener
public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("MyListener 监听到 ServletContext 初始化");
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("MyListener 监听到 ServletContext 销毁");
    }
}
  1. 在启动类上使用 @ServletComponentScan 注解,扫描以上刚刚声明的 Servlet、Filter 和 Listener,并将它们注册到容器中使用,代码如下。
package net.biancheng.www;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class SpringBootServletApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootServletApplication.class, args);
    }
}
  1. 启动 Spring Boot,控制台日志出入如下。
  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::                (v2.5.1)

2021-06-23 14:07:04.202  INFO 10200 --- [           main] n.b.www.SpringBootServletApplication     : Starting SpringBootServletApplication using Java 1.8.0_131 on LAPTOP-C67MRMAG with PID 10200 (D:\spring-boot-servlet\target\classes started by 79330 in D:\spring-boot-servlet)
2021-06-23 14:07:04.205  INFO 10200 --- [           main] n.b.www.SpringBootServletApplication     : No active profile set, falling back to default profiles: default
2021-06-23 14:07:05.169  INFO 10200 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-06-23 14:07:05.180  INFO 10200 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-06-23 14:07:05.180  INFO 10200 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-06-23 14:07:05.245  INFO 10200 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-06-23 14:07:05.245  INFO 10200 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 984 ms
MyListener 监听到 ServletContext 初始化
MyFiler 初始化
2021-06-23 14:07:05.543  INFO 10200 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-06-23 14:07:05.550  INFO 10200 --- [           main] n.b.www.SpringBootServletApplication     : Started SpringBootServletApplication in 1.853 seconds (JVM running for 2.764)
MyFiler doFilter

由以上日志输出可以看出,自定义的过滤器 Filter 和 监听器 Listener 都已经生效。

  1. 浏览器访问“http://localhost:8080/myServlet”,结果如下。

由上图可知,自定义的 Servlet 也已经生效了。

使用 RegistrationBean 注册

我们还可以在配置类中使用 RegistrationBean 来注册原生 Web 组件,不过这种方式相较于注解方式要繁琐一些。使用这种方式注册的原生 Web 组件,不再需要使用 @WebServlet 、@WebListener 和 @WebListener 等注解。

RegistrationBean 是个抽象类,负责将组件注册到 Servlet 容器中,Spring 提供了三个它的实现类,分别用来注册 Servlet、Filter 和 Listener。

  • ServletRegistrationBean:Servlet 的注册类
  • FilterRegistrationBean:Filter 的注册类
  • ServletListenerRegistrationBean:Listener 的注册类

我们可以在配置类中,使用 @Bean 注解将 ServletRegistrationBean、FilterRegistrationBean 和 ServletListenerRegistrationBean 添加 Spring 容器中,并通过它们将我们自定义的 Servlet、Filter 和 Listener 组件注册到容器中使用。

示例 2

  1. 创建自定义 Servlet,代码如下。
package net.biancheng.www.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class MyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write("Spring Boot Servlet");
        writer.close();
    }
}
  1. 创建自定义的 Filter,代码如下。
package net.biancheng.www.filter;
import javax.servlet.*;
import java.io.IOException;
public class MyFiler implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("MyFiler 初始化");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("MyFiler doFilter");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
        System.out.println("MyFiler 销毁");
    }
}
  1. 创建自定义的 Listener,代码如下。
package net.biancheng.www.Listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
//监听 ServletContext 的初始化和销毁过程
public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("MyListener 监听到 ServletContext 初始化");
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("MyListener 监听到 ServletContext 销毁");
    }
}
  1. 创建一个配置类 MyConfig,使用 @Bean 注解将 ServletRegistrationBean、FilterRegistrationBean 和 ServletListenerRegistrationBean 添加到 Spring 容器中,并分别使用它们注册我们自定义的 Servlet、Filter 和 Listener,示例代码如下。
package net.biancheng.www.config;
import net.biancheng.www.Listener.MyListener;
import net.biancheng.www.filter.MyFiler;
import net.biancheng.www.servlet.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class MyConfig {
    /**
     * 注册 servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        MyServlet myServlet = new MyServlet();
        return new ServletRegistrationBean(myServlet, "/myServlet");
    }
    /**
     * 注册过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        MyFiler myFiler = new MyFiler();
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFiler);
        //注册该过滤器需要过滤的 url
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/myServlet"));
        return filterRegistrationBean;
    }
    /**
     * 注册监听器
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean() {
        MyListener myListener = new MyListener();
        return new ServletListenerRegistrationBean(myListener);
    }
}
  1. 启动 Spring Boot,控制台日志出入如下。
  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::                (v2.5.1)

2021-06-23 14:39:16.338  INFO 8684 --- [           main] n.b.www.SpringBootServletApplication     : Starting SpringBootServletApplication using Java 1.8.0_131 on LAPTOP-C67MRMAG with PID 8684 (D:\spring-boot-servlet\target\classes started by 79330 in D:\spring-boot-servlet)
2021-06-23 14:39:16.340  INFO 8684 --- [           main] n.b.www.SpringBootServletApplication     : No active profile set, falling back to default profiles: default
2021-06-23 14:39:17.059  INFO 8684 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-06-23 14:39:17.069  INFO 8684 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-06-23 14:39:17.070  INFO 8684 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.46]
2021-06-23 14:39:17.138  INFO 8684 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-06-23 14:39:17.138  INFO 8684 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 766 ms
MyListener 监听到 ServletContext 初始化
MyFiler 初始化
2021-06-23 14:39:17.390  INFO 8684 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-06-23 14:39:17.396  INFO 8684 --- [           main] n.b.www.SpringBootServletApplication     : Started SpringBootServletApplication in 1.379 seconds (JVM running for 2.19)

由以上日志输出可以看出,自定义的过滤器 Filter 和监听器 Listener 都已经生效。

  1. 浏览器访问“http://localhost:8080/myServlet”,结果如下图。

由上图可知,自定义的 Servlet 也已经被注册生效了。

Spring Boot JDBC访问数据库

对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 都默认采用整合 Spring Data 的方式进行统一处理,通过大量自动配置,来简化我们对数据访问层的操作,我们只需要进行简单的设置即可实现对书层的访问。本节,我们将学习如何在 Spring Boot 中使用 JDBC 进行数据访问。

导入 JDBC 场景启动器

Spring Boot 将日常企业应用研发中的各种场景都抽取出来,做成一个个的场景启动器(Starter),场景启动器中整合了该场景下各种可能用到的依赖,让用户摆脱了处理各种依赖和配置的困扰。

想要在 Spring Boot 中使用 JDBC 进行数据访问,第一步就是要在 pom.xml 中导入 JDBC 场景启动器:spring-boot-starter-data-jdbc,代码如下。

<!--导入JDBC的场景启动器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

查看 spring-boot-starter-data-jdbc 的依赖树,可以看到,该场景启动器默认引入了一个数据源:HikariCP,如下图所示。

导入数据库驱动

JDBC 的场景启动器中并没有导入数据库驱动,我们需要根据自身的需求引入所需的数据库驱动。例如,访问 MySQL 数据库时,需要导入 MySQL 的数据库驱动:mysql-connector-java,示例代码如下。

<!--导入数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

Spring Boot 默认为数据库驱动程序做了版本仲裁,所以我们在导入数据库驱动时,可以不再声明版本。需要注意的是,数据库驱动的版本必须与数据库的版本相对应。

配置数据源

在导入了 JDBC 场景启动器和数据库驱动后,接下来我们就可以在配置文件(application.properties/yml)中配置数据源了,示例代码(application.yml)如下。

#数据源连接信息
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/bianchengbang_jdbc
    driver-class-name: com.mysql.cj.jdbc.Driver

注意:此处了解即可,下一节将具体介绍 Spring Boot 的数据源配置及其原理。

测试

Spring Boot 提供了一个名为 JdbcTemplate 的轻量级数据访问工具,它是对 JDBC 的封装。Spring Boot 对 JdbcTemplate 提供了默认自动配置,我们可以直接使用 @Autowired 或构造函数将它注入到 bean 中使用。

下面,我们通过 JdbcTemplate 来实现对数据库的访问,代码如下。

package net.biancheng.www;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.sql.SQLException;
@SpringBootTest
class SpringBootJdbcApplicationTests {
    //数据源组件
    @Autowired
    DataSource dataSource;
    //用于访问数据库的组件
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Test
    void contextLoads() throws SQLException {
        System.out.println("默认数据源为:" + dataSource.getClass());
        System.out.println("数据库连接实例:" + dataSource.getConnection());
        //访问数据库
        Integer i = jdbcTemplate.queryForObject("SELECT count(*) from `user`", Integer.class);
        System.out.println("user 表中共有" + i + "条数据。");
    }
}

运行该测试代码,结果如下。

默认数据源为:class com.zaxxer.hikari.HikariDataSource
数据库连接实例:HikariProxyConnection@659763564 wrapping com.mysql.cj.jdbc.ConnectionImpl@59edb4f5
user 表中共有1条数据。

通过以上运行结果可以看出,Spring Boot 默认使用 HikariCP 作为其数据源,对数据库的访问。

Spring Boot数据源配置原理

在数据库访问过程中,“数据源”无疑是最重要的概念之一,它不仅可以对与数据库访问相关的各种参数进行封装和统一管理,还可以管理数据库连接池,提高数据库连接性能。

目前,在市面上有很多优秀的开源数据源,例如 DBCP、C3P0、Druid、HikariCP 等等。在 Spring Boot 2.x 中,则采用目前性能最佳的 HikariCP 作为其默认数据源。

DataSourceAutoConfiguration

我们知道,Spring Boot 中几乎所有的默认配置都是通过配置类 XxxAutoConfiguration 进行配置的,Spring Boot 数据源也不例外,它的自动配置类是:DataSourceAutoConfiguration。

DataSourceAutoConfiguration 中共包括以下 5 个内部静态类:

  • EmbeddedDatabaseCondition
  • PooledDataSourceAvailableCondition
  • PooledDataSourceCondition
  • PooledDataSourceConfiguration(池化数据源自动配置类)
  • EmbeddedDatabaseConfiguration(内嵌数据源自动配置类)

其中,PooledDataSourceConfiguration 和 EmbeddedDatabaseConfiguration 为使用了 @Configuration 注解的自动配置类,其余 3 个为限制条件类。

EmbeddedDatabaseConfiguration

顾名思义,EmbeddedDatabaseConfiguration 是内嵌数据源的自动配置类,该类中并没有任何的方法实现,它的主要功能都是通过 @Import 注解引入 EmbeddedDataSourceConfiguration 类来实现的。

@Import({EmbeddedDataSourceConfiguration.class})

EmbeddedDataSourceConfiguration 向容器中添加了一个 Spring Boot 内嵌的数据源,该数据源支持 HSQL,H2 和 DERBY 三种数据库,其部分代码如下。

@Configuration(
    proxyBeanMethods = false
)
@EnableConfigurationProperties({DataSourceProperties.class})
public class EmbeddedDataSourceConfiguration implements BeanClassLoaderAware {
    private ClassLoader classLoader;
    public EmbeddedDataSourceConfiguration() {
    }
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }
    //向容器中添加 Spring Boot 内嵌的数据源
    @Bean(
        destroyMethod = "shutdown"
    )
    public EmbeddedDatabase dataSource(DataSourceProperties properties) {
        return (new EmbeddedDatabaseBuilder()).setType(EmbeddedDatabaseConnection.get(this.classLoader).getType()).setName(properties.determineDatabaseName()).build();
    }
}

通过上面的分析,我们知道自动配置类 EmbeddedDatabaseConfiguration 的作用是向容器中添加一个内嵌的数据源(DataSource),但这是有条件限制的。

在 EmbeddedDatabaseConfiguration 类上还使用一个 @Conditional 注解,该注解使用了 DataSourceAutoConfiguration 的内部限制条件类 EmbeddedDatabaseCondition 来进行条件判断。

@Conditional({DataSourceAutoConfiguration.EmbeddedDatabaseCondition.class})

EmbeddedDatabaseCondition 主要用来检测容器中是否已经存在池化数据源(PooledDataSource)。若容器中存在池化数据源时,则 EmbeddedDatabaseConfiguration 不能被实例化。只有当容器中不存在池化数据源时,EmbeddedDatabaseConfiguration 才能被实例化,才能向容器中添加内嵌数据源(EmbeddedDataSource)。

PooledDataSourceConfiguration

PooledDataSourceConfiguration 是池化数据源的自动配置类,该类上使用了一个 @Conditional 注解,该注解使用了 DataSourceAutoConfiguration 的内部限制条件类 PooledDataSourceCondition 来进行条件判断。

@Conditional({DataSourceAutoConfiguration.PooledDataSourceCondition.class})

PooledDataSourceCondition 与 EmbeddedDatabaseCondition 一样,也是用来检测容器中是否已经存在池化数据源的,但不同的是,PooledDataSourceConfiguration 是只有当容器中存在池化数据源时, 才可以被实例化,才可以向容器中添加池化数据源。

与 EmbeddedDatabaseConfiguration 一样,PooledDataSourceConfiguration 类中也没有任何的方法实现,它的所有功能都是通过 @Import 注解引入其他的类实现的。

@Import({Hikari.class, Tomcat.class, Dbcp2.class, OracleUcp.class, Generic.class, DataSourceJmxConfiguration.class})

PooledDataSourceConfiguration 通过 @Import 注解引入了 Hikari、Tomcat、Dbcp2、OracleUcp 和 Generic 五个数据源配置类,它们都是 DataSourceConfiguration 的内部类,且它们的功能类似,都是向容器中添加指定的数据源。

下面我们以 Hikari 为例进行分析,Hikari 的源码如下。

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({HikariDataSource.class})
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
    name = {"spring.datasource.type"},
    havingValue = "com.zaxxer.hikari.HikariDataSource",
    matchIfMissing = true
)
static class Hikari {
    Hikari() {
    }
    @Bean
    @ConfigurationProperties(
        prefix = "spring.datasource.hikari"
    )
    HikariDataSource dataSource(DataSourceProperties properties) {
        HikariDataSource dataSource = (HikariDataSource)DataSourceConfiguration.createDataSource(properties, HikariDataSource.class);
        if (StringUtils.hasText(properties.getName())) {
            dataSource.setPoolName(properties.getName());
        }
        return dataSource;
    }
}

在 Hikari 类中,主要使用以下注解:

  • @Configuration:表示当前类是一个配置类;
  • @ConditionalOnMissingBean({DataSource.class}):表示容器中没有用户自定义的数据源时,该配置类才会被实例化;
  • @ConditionalOnClass({HikariDataSource.class}) :表示必须在类路径中存在 HikariDataSource 类时,Hikari 才会实例化。而 HikariDataSource 类是由 spring- boot-starter-jdbc 默认将其引入的,因此只要我们在 pom.xml 中引入了该 starter, Hikari 就会被实例化(这也是 Spring Boot 2.x 默认使用 HikariCP 作为其数据源的原因)。;
  • @ConditionalOnProperty( name = {“spring.datasource.type”},havingValue = “com.zaxxer.hikari.HikariDataSource”,matchIfMissing = true): 表示当 Spring Boot 配置文件中,配置了 spring.datasource.type = com.zaxxer.hikari.HikariDataSource(明确指定使用 Hikari 数据源)或者不配置 spring.datasource.type(即默认情况)时,Hikari 才会被实例化。

Hikari 类通过 @Bean 注解向容器中添加了 HikariDataSource 组件,该组件的实例对象是通过调用 DataSourceConfiguration 的 createDataSource() 方法得到的,代码如下。

@Bean
@ConfigurationProperties(
    prefix = "spring.datasource.hikari"
)
HikariDataSource dataSource(DataSourceProperties properties) {
    HikariDataSource dataSource = (HikariDataSource)DataSourceConfiguration.createDataSource(properties, HikariDataSource.class);
    if (StringUtils.hasText(properties.getName())) {
        dataSource.setPoolName(properties.getName());
    }
    return dataSource;
}

在 createDataSource() 方法中,调用 DataSourceProperties 的 initializeDataSourceBuilder() 来初始化 DataSourceBuilder,源码如下。

protected static <T> T createDataSource(DataSourceProperties properties, Class<? extends DataSource> type) {
    return properties.initializeDataSourceBuilder().type(type).build();
}

initializeDataSourceBuilder() 方法通过调用 DataSourceBuilder 的 create() 方法创建 DataSourceBuilder 对象,并根据 Spring Boot 的配置文件(application.properties/yml)中的配置,依次设置数据源类型、驱动类名、连接 url、 用户名和密码等信息。

public DataSourceBuilder<?> initializeDataSourceBuilder() {
    return DataSourceBuilder.create(this.getClassLoader()).type(this.getType()).
          driverClassName(this.determineDriverClassName()).url(this.determineUrl()).username(this.determineUsername()).password(this.determinePassword());
}

上面提到 spring.datasource.type 默认是可以不用配置的,因此在 createDataSource() 方法在获取到回传回来的 DataSourceBuilder 对象后,还需要将其 type 属性再次设置为 HikariDataSource,并调用 DataSourceBuilder 的 build() 方法,完成 HikariDataSource 的初始化。

dataSource() 方法获得数据源对象,并设置了连接池的名字(name),注入到容器中。

自此,我们就完成了对 Spring Boot 数据源自动配置原理的分析。

总结

通过对 Spring Boot 数据源自动配置原理的分析可知:

  • 在用户没有配置数据源的情况,若容器中存在 HikariDataSource 类,则 Spring Boot 就会自动实例化 Hikari,并将其作为其数据源。
  • Spring Boot 的 JDBC 场景启动器(spring-boot-starter-data-jdbc)通过 spring- boot-starter-jdbc 默认引入了 HikariCP 数据源(包含 HikariDataSource 类),因此 Spring Boot 默认使用 HikariCP 作为其数据源。

Spring Boot整合Druid数据源

Spring Boot 2.x 默认使用 HikariCP 作为数据源,我们只要在项目中导入了 Spring Boot 的 JDBC 场景启动器,便可以使用 HikariCP 数据源获取数据库连接,对数据库进行增删改查等操作。

HikariCP 是目前市面上性能最好的数据源产品,但在实际的开发过程中,企业往往更青睐于另一款数据源产品:Druid,它是目前国内使用范围最广的数据源产品。

Druid 是阿里巴巴推出的一款开源的高性能数据源产品,Druid 支持所有 JDBC 兼容的数据库,包括 Oracle、MySQL、SQL Server 和 H2 等等。Druid 不仅结合了 C3P0、DBCP 和 PROXOOL 等数据源产品的优点,同时还加入了强大的监控功能。通过 Druid 的监控功能,可以实时观察数据库连接池和 SQL 的运行情况,帮助用户及时排查出系统中存在的问题。

Druid 不是 Spring Boot 内部提供的技术,它属于第三方技术,我们可以通过以下两种方式进行整合:

  • 自定义整合 Druid
  • 通过 starter 整合 Druid

接下来我们将结合 Spring Boot 项目 spring-boot-adminex,分别对这两种整合方式进行讲解。

自定义整合 Druid

自定义整合 Druid 是指:根据 Druid 官方文档和自身的需求,通过手动创建 Druid 数据源的方式,将 Druid 整合到 Spring Boot 中。

1. 引入 Druid 依赖

Druid 0.1.18 之后版本都已经发布到 Maven 中央仓库中了,所以我们只需要在项目的 pom.xml 中引入 Druid 的依赖(dependency ),即可将 Druid 导入到 Spring Boot 项目中。

在 spring-boot-adminex 的 pom.xml 中添加以下代码,引入 JDBC 场景启动器、MySql 数据库驱动 和 Druid 依赖。

<!--导入 JDBC 场景启动器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!--导入数据库驱动-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!--采用自定义方式整合 druid 数据源-->
<!--自定义整合需要编写一个与之相关的配置类-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.6</version>
</dependency>

2. 创建数据源

我们知道,Spring Boot 使用 HikariCP 作为其默认数据源,但其中有一个十分重要的条件,如下图。

@ConditionalOnMissingBean(DataSource.class) 的含义是:当容器中没有 DataSource(数据源类)时,Spring Boot 才会使用 HikariCP 作为其默认数据源。 也就是说,若我们向容器中添加 Druid 数据源类(DruidDataSource,继承自 DataSource)的对象时,Spring Boot 就会使用 Druid 作为其数据源,而不再使用 HikariCP。

例如,在 net.biancheng.www.config 包中,创建一个名为 MyDataSourceConfig 的配置类,并将 Druid 数据源对象添加到容器中,代码如下。

package net.biancheng.www.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
public class MyDataSourceConfig implements WebMvcConfigurer {
    /**
     * 当向容器中添加了 Druid 数据源
   * 使用 @ConfigurationProperties 将配置文件中 spring.datasource 开头的配置与数据源中的属性进行绑定
     * @return
     */
    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource druidDataSource = new DruidDataSource();
        //我们一般不建议将数据源属性硬编码到代码中,而应该在配置文件中进行配置(@ConfigurationProperties 绑定)
//        druidDataSource.setUrl("jdbc:mysql://127.0.0.1:3306/bianchengbang_jdbc");
//        druidDataSource.setUsername("root");
//        druidDataSource.setPassword("root");
//        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return druidDataSource;
    }
}

在配置文件 application.yml 中添加以下数据源配置,它们会与与 Druid 数据源中的属性进行绑定,代码如下。

#数据源连接信息
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://127.0.0.1:3306/bianchengbang_jdbc
    driver-class-name: com.mysql.cj.jdbc.Driver

注:配置类创建 Druid 数据源对象时,应该尽量避免将数据源信息(例如 url、username 和 password 等)硬编码到代码中,而应该通过 @ConfigurationProperties(“spring.datasource”) 注解,将 Druid 数据源对象的属性与配置文件中的以“spring.datasource”开头的配置进行绑定。

至此,我们就已经将数据源从 HikariCP 切换到了 Druid 了。

示例 1

接下来,我们可以使用 Spring Boot 提供的默认测试类 SpringBootAdminexApplicationTests 进行简单的测试,来验证数据源类型是否为 Druid 以及是否能正常获取数据库连接、访问数据库,代码如下。

package net.biancheng.www;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.sql.SQLException;
@SpringBootTest
class SpringBootAdminexApplicationTests {
    //数据源组件
    @Autowired
    DataSource dataSource;
    //用于访问数据库的组件
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Test
    void contextLoads() throws SQLException {
        System.out.println("默认数据源为:" + dataSource.getClass());
        System.out.println("数据库连接实例:" + dataSource.getConnection());
        //访问数据库
        Integer i = jdbcTemplate.queryForObject("SELECT count(*) from `user`", Integer.class);
        System.out.println("user 表中共有" + i + "条数据。");
    }
}

运行测试程序,结果如下。

默认数据源为:class com.alibaba.druid.pool.DruidDataSource
数据库连接实例:com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@46e190ed
user 表中共有2条数据。

根据以上运行结果可以看出,数据源已经成功地切换到了 Druid 数据源,且通过它也可以正常的获取数据库连接,访问数据库。

3. 开启 Druid 内置监控页面

Druid 内置提供了一个名为 StatViewServlet 的 Servlet,这个 Servlet 可以开启 Druid 的内置监控页面功能, 展示 Druid 的统计信息,它的主要用途如下:

  • 提供监控信息展示的 html 页面
  • 提供监控信息的 JSON API

注意:使用 StatViewServlet,建议使用 Druid 0.2.6 以上版本。

根据 Druid 官方文档-配置_StatViewServlet 配置,StatViewServlet 是一个标准的 javax.servlet.http.HttpServlet,想要开启 Druid 的内置监控页面,需要将该 Servlet 配置在 Web 应用中的 WEB-INF/web.xml 中,web.xml 中配置如下。

<servlet>
    <servlet-name>DruidStatView</servlet-name>
    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DruidStatView</servlet-name>
    <url-pattern>/druid/*</url-pattern>
</servlet-mapping>

我们知道,Spring Boot 项目中是没有 WEB-INF/web.xml 的,因此我们可以在配置类中,通过 ServletRegistrationBean 将 StatViewServlet 注册到容器中,来开启 Druid 的内置监控页面。

关于 ServletRegistrationBean 的详细使用,请参考 Spring Boot注册Web原生组件(Servlet、Filter、Listener)

示例 2

  1. 在 MyDataSourceConfig 配置类中添加以下代码,将 StatViewServlet 注入到容器中,开启 Druid 内置监控页面功能。
/**
* 开启 Druid 数据源内置监控页面
*
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet() {
    StatViewServlet statViewServlet = new StatViewServlet();
    //向容器中注入 StatViewServlet,并将其路径映射设置为 /druid/*
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(statViewServlet, "/druid/*");
    //配置监控页面访问的账号和密码(选配)
    servletRegistrationBean.addInitParameter("loginUsername", "admin");
    servletRegistrationBean.addInitParameter("loginPassword", "123456");
    return servletRegistrationBean;
}
  1. 启动 Spring Boot,浏览器访问“http://localhost:8080/druid”,即可访问 Druid 的内置监控页面的登陆页,结果如下。

  1. 在登陆页输入框内,分别输入我们自定义的用户名(loginUsername)和密码(loginPassword),点击 Sign in 按钮访问监控页面,如下图。

4. 开启 SQL 监控

Druid 内置提供了一个 StatFilter,通过它可以开启 Druid 的 SQL 监控功能,对 SQL 进行监控。

StatFilter 的别名是 stat,这个别名的映射配置信息保存在 druid-xxx.jar!/META-INF/druid-filter.properties 中。Druid 官方文档-配置_StatFilter 中给出了在 Spring 中配置该别名(stat)开启 Druid SQL 监控的方式,配置如下。

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
... ...
<property name="filters" value="stat" />
</bean>

根据以上配置我们可以看出,只要在 dataSource 的 Bean 中添加一个取值为“stat”的“filters”属性,就能开启 Druid SQL 监控,因此我们只要将该配置转换为在配置类中进行即可,代码如下。

@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() throws SQLException {
    DruidDataSource druidDataSource = new DruidDataSource();
    //设置 filters 属性值为 stat,开启 SQL 监控
    druidDataSource.setFilters("stat");
    return druidDataSource; 
}

示例 3

  1. 为了验证 Druid SQL 监控是否开启,我们需要在 IndexController 中添加一个能够查询数据库的方法,代码如下。
@Controller
public class IndexController {
    //自动装配 jdbcTemplate
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 访问"/testSql",访问数据库
     * @return
     */
    @ResponseBody
    @GetMapping("/testSql")
    public String testSql() {
        String SQL = "SELECT count(*) from `user`";
        Integer integer = jdbcTemplate.queryForObject(SQL, Integer.class);
        return integer.toString();
    }
}
  1. 重启 Spring Boot,浏览器访问“http://localhost:8080/testSql”,结果如下图。

  1. 访问 Druid 的内置监控页面,切换到 SQL 监控模块,可以看到 Druid SQL 监控已经开启,如下图。

5. 开启防火墙

Druid 内置提供了一个 WallFilter,使用它可以开启防火墙功能,防御 SQL 注入攻击。

WallFilter 的别名是 wall,这个别名映射配置信息保存在 druid-xxx.jar!/META-INF/druid-filter.properties 中。Druid 官方文档-配置 wallfilter 中给出了在 Spring 中使用该别名(wall)开启防火墙的方式,配置如下。

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
... ...
<property name="filters" value="wall" />
</bean>

WallFilter 可以结合其他 Filter 一起使用,例如:

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    ...
    <property name="filters" value="wall,stat"/>
</bean>

根据以上配置我们可以看出,只要在 dataSource 的 Bean 中添加一个取值为“wall”的“filters”属性,就能开启 Druid 的防火墙功能,因此我们只需要在配置类中为 dataSource 的 filters 属性再添加一个“wall”即可(多个属性值之间使用逗号“,”隔开),代码如下。

@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() throws SQLException {
    DruidDataSource druidDataSource = new DruidDataSource();
    //同时开启 sql 监控(stat) 和防火墙(wall),中间用逗号隔开。
    //开启防火墙能够防御 SQL 注入攻击
    druidDataSource.setFilters("stat,wall");
    return druidDataSource;
}

示例 4

  1. 重启 Spring Boot,浏览器访问“http://localhost:8080/testSql”,结果如下图。

  1. 访问 Druid 的内置监控页面,切换到 SQL 防火墙,可以看到 Druid 防火墙已经开启,如下图。

6. 开启 Web-JDBC 关联监控

Druid 还内置提供了一个名为 WebStatFilter 的过滤器,它可以用来监控与采集 web-jdbc 关联监控的数据。

根据 Druid 官方文档-配置_配置WebStatFilter,想要开启 Druid 的 Web-JDBC 关联监控,只需要将 WebStatFilter 配置在 Web 应用中的 WEB-INF/web.xml 中即可,web.xml 配置如下。

<filter>
    <filter-name>DruidWebStatFilter</filter-name>
    <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
    <init-param>
        <param-name>exclusions</param-name>
        <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>DruidWebStatFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Spring Boot 项目中是没有 WEB-INF/web.xml 的,但是我们可以在配置类中,通过 FilterRegistrationBean 将 WebStatFilter 注入到容器中,来开启 Druid 的 Web-JDBC 关联监控。

配置类中示例代码如下。

/**
* 向容器中添加 WebStatFilter
* 开启内置监控中的 Web-jdbc 关联监控的数据
* @return
*/
@Bean
public FilterRegistrationBean druidWebStatFilter() {
    WebStatFilter webStatFilter = new WebStatFilter();
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(webStatFilter);
    // 监控所有的访问
    filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
    // 监控访问不包括以下路径
    filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
}

示例 5

  1. 重启 Spring Boot,浏览器访问“http://localhost:8080/testSql”,结果如下图。

  1. 浏览器访问 AdminEx 系统的任意页面,然后再访问 Druid 的内置监控页面,切换到 Web 应用模块,可以看到 Druid 的 Web 监控已经开启,如下图。

与此同时,URI 监控和 Session 监控也都被开启,如下图。

通过 starter 整合 Druid

Druid 可以说是国内使用最广泛的数据源连接池产品,但到目前为止 Spring Boot 官方只对 Hikari、Tomcat、Dbcp2 和 OracleUcp 等 4 种数据源产品提供了自动配置支持,对于其他的数据源连接池产品(包括 Druid),则并没有提供自动配置支持。这就导致用户只能通过自定义的方式(第一种整合方式)整合 Druid,非常繁琐。

为了解决这一问题,于是阿里官方提供了 Druid Spring Boot Starter,它可以帮助我们在 Spring Boot 项目中,轻松地整合 Druid 的数据库连接池和监控功能。

使用 Druid Spring Boot Starter 将 Druid 与 Spring Boot 整合,步骤如下。

1. 引入 Druid Spring Boot Starter 依赖

在 Spring Boot 项目的 pom.xml 中添加以下依赖,引入 Druid Spring Boot Starter(点击查询最新版本),示例代码如下。

<!--添加 druid 的 starter-->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.17</version>
</dependency>

2. 配置属性

Druid Spring Boot Starter 已经将 Druid 数据源中的所有模块都进行默认配置,我们也可以通过 Spring Boot 配置文件(application.properties/yml)来修改 Druid 各个模块的配置,否则将使用默认配置。

在 Spring Boot 配置文件中配置以下内容:

  • JDBC 通用配置
  • Druid 数据源连接池配置
  • Druid 监控配置
  • Druid 内置 Filter 配置

这些配置内容既可以在 application.properties 中进行配置,也可以在 application.yml 中尽心配置,当配置内容较多时,我们通常推荐使用 application.yml(示例中使用的是 application.yml)。

JDBC 通用配置

我们可以在 Spring Boot 的配置文件中对 JDBC 进行通用配置,例如,数据库用户名、数据库密码、数据库 URL 以及 数据库驱动等等,示例代码如下。

  ################################################## JDBC 通用配置  ##########################################
spring:
  datasource:
    username: root                                                                   #数据库登陆用户名
    password: root                                                                   #数据库登陆密码
    url: jdbc:mysql://127.0.0.1:3306/bianchengbang_jdbc                              #数据库url
    driver-class-name: com.mysql.cj.jdbc.Driver                                      #数据库驱动

Druid 数据源连接池配置

我们还可以在 Spring Boot 的配置文件中对 Druid 数据源连接池进行配置,示例代码如下。

  ################################################## Druid连接池的配置 ##########################################
spring:
  datasource:
    druid:
      initial-size: 5                                                                 #初始化连接大小
      min-idle: 5                                                                     #最小连接池数量
      max-active: 20                                                                  #最大连接池数量
      max-wait: 60000                                                                 #获取连接时最大等待时间,单位毫秒
      time-between-eviction-runs-millis: 60000                                        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      min-evictable-idle-time-millis: 300000                                          #配置一个连接在池中最小生存的时间,单位是毫秒
      validation-query: SELECT 1 FROM DUAL                                            #测试连接
      test-while-idle: true                                                           #申请连接的时候检测,建议配置为true,不影响性能,并且保证安全性
      test-on-borrow: false                                                           #获取连接时执行检测,建议关闭,影响性能
      test-on-return: false                                                           #归还连接时执行检测,建议关闭,影响性能
      pool-prepared-statements: false                                                 #是否开启PSCache,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql下建议关闭
      max-pool-prepared-statement-per-connection-size: 20                             #开启poolPreparedStatements后生效
      filters: stat,wall                                                              #配置扩展插件,常用的插件有=>stat:监控统计  wall:防御sql注入
      connection-properties: 'druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000' #通过connectProperties属性来打开mergeSql功能;慢SQL记录

Druid 监控配置

我们还可以在 Spring Boot 的配置文件中对 Druid 内置监控页面、Web-JDBC 关联监控和 Spring 监控等功能进行配置,示例代码如下。

  ###################################################### Druid 监控配置信息  ##########################################
spring:
  datasource:
    druid:
      # StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
      stat-view-servlet:
        enabled: true                                                                 #是否开启内置监控页面,默认值为 false
        url-pattern: '/druid/*'                                                       #StatViewServlet 的映射路径,即内置监控页面的访问地址
        reset-enable: true                                                            #是否启用重置按钮
        login-username: admin                                                         #内置监控页面的登录页用户名 username
        login-password: admin                                                         #内置监控页面的登录页密码 password
      # WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
      web-stat-filter:
        enabled: true                                                                 #是否开启内置监控中的 Web-jdbc 关联监控的数据
        url-pattern: '/*'                                                             #匹配路径
        exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'                     #排除路径
        session-stat-enable: true                                                     #是否监控session
      # Spring监控配置,说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置
      aop-patterns: net.biancheng.www.*                                               #Spring监控AOP切入点,如x.y.z.abc.*,配置多个英文逗号分隔

Druid 内置 Filter 配置

Druid Spring Boot Starter 对以下 Druid 内置 Filter,都提供了默认配置:

  • StatFilter
  • WallFilter
  • ConfigFilter
  • EncodingConvertFilter
  • Slf4jLogFilter
  • Log4jFilter
  • Log4j2Filter
  • CommonsLogFilter

我们可以通过 spring.datasource.druid.filters=stat,wall … 的方式来启用相应的内置 Filter,不过这些 Filter 使用的都是默认配置。如果默认配置不能满足我们的需求,我们还可以在配置文件使用 spring.datasource.druid.filter.* 对这些 Filter 进行配置,示例代码如下。

#  ####################################################### Druid 监控配置信息  ##########################################
spring:
  datasource:
    druid:
     # 对配置已开启的 filters 即 stat(sql 监控)  wall(防火墙)
      filter:
        #配置StatFilter (SQL监控配置)
        stat:
          enabled: true                                                               #开启 SQL 监控
          slow-sql-millis: 1000                                                       #慢查询
          log-slow-sql: true                                                          #记录慢查询 SQL
        #配置WallFilter (防火墙配置)
        wall:
          enabled: true                                                               #开启防火墙
          config:
            update-allow: true                                                        #允许更新操作
            drop-table-allow: false                                                   #禁止删表操作
            insert-allow:  true                                                       #允许插入操作
            delete-allow: true                                                        #删除数据操作

在配置 Druid 内置 Filter 时,需要先将对应 Filter 的 enabled 设置为 true,否则内置 Filter 的配置不会生效。

以上所有内容都只是示例配置,Druid Spring Boot Starter 并不是只支持以上属性,它支持 DruidDataSource 内所有具有 setter 方法的属性。

至此,我们就完成了使用 Druid Spring Boot Starter 整合 Druid 的全部过程,至于验证步骤请参考自定义整合。

总结

无论是自定义整合还是通过 Druid Spring Boot Starter 整合,都能实现 Spring Boot 整合 Druid 数据源的目的,它们都各有利弊。

  • 根据官方文档,自定义整合 Druid 数据源能够更加清晰地了解 Druid 的各种功能及其实现方式,但整合过程繁琐。
  • 通过 Druid Spring Boot Starter 整合 Druid 数据源,则更加方便快捷,大大简化了整合过程,但无法清晰地了解 Druid 的功能内部的实现方式和原理。

这里,我们更加推荐使用 Druid Spring Boot Starter 进行整合,毕竟这种整合方式大大简化了整个整合的过程。

Spring Boot整合MyBatis

MyBatis 是一个半自动化的 ORM 框架,所谓半自动化是指 MyBatis 只支持将数据库查出的数据映射到 POJO 实体类上,而实体到数据库的映射则需要我们自己编写 SQL 语句实现,相较于Hibernate 这种完全自动化的框架,Mybatis 更加灵活,我们可以根据自身的需求编写 sql 语句来实现复杂的数据库操作。

随着 Spring Boot 越来越流行,越来越多的被厂商及开发者所认可,MyBatis 也开发了一套基于 Spring Boot 模式的 starter:mybatis-spring-boot-starter。本节我们就介绍下如何在 Spring Boot 项目中整合 MyBatis。

引入依赖

Spring Boot 整合 MyBatis 的第一步,就是在项目的 pom.xml 中引入 mybatis-spring-boot-starter 的依赖,示例代码如下。

<!--引入 mybatis-spring-boot-starter 的依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.0</version>
</dependency>

配置 MyBatis

在 Spring Boot 的配置文件(application.properties/yml)中对 MyBatis 进行配置,例如指定 mapper.xml 的位置、实体类的位置、是否开启驼峰命名法等等,示例代码如下。

###################################### MyBatis 配置######################################
mybatis:
  # 指定 mapper.xml 的位置
  mapper-locations: classpath:mybatis/mapper/*.xml
  #扫描实体类的位置,在此处指明扫描实体类的包,在 mapper.xml 中就可以不写实体类的全路径名
  type-aliases-package: net.biancheng.www.bean
  configuration:
    #默认开启驼峰命名法,可以不用设置该属性
    map-underscore-to-camel-case: true 

注意:使用 MyBatis 时,必须配置数据源信息,例如数据库 URL、数据库用户型、数据库密码和数据库驱动等。

创建实体类

在指定的数据库内创建一个 user 表,并插入一些数据,如下表。

id user_id user_name password email
1 001 admin admin 1234567@qq.com
2 002 user 123456 987654@qq.com
3 003 bianchengbang qwertyuiop bianchengbang@sina.com根据数据库 user 表,创建相应的实体类 User,代码如下。
package net.biancheng.www.bean;
public class User {
    private Integer id;
    private String userId;
    private String userName;
    private String password;
    private String email;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId == null ? null : userId.trim();
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName == null ? null : userName.trim();
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }
}

创建 Mapper 接口

在 net.biancheng.www.mapper 中创建一个 UserMapper 接口,并在该类上使用 @Mapper 注解,代码如下。

package net.biancheng.www.mapper;
import net.biancheng.www.bean.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
    //通过用户名密码查询用户数据
    User getByUserNameAndPassword(User user);
}

当 mapper 接口较多时,我们可以在 Spring Boot 主启动类上使用 @MapperScan 注解扫描指定包下的 mapper 接口,而不再需要在每个 mapper 接口上都标注 @Mapper 注解。

创建 Mapper 映射文件

在配置文件 application.properties/yml 通过 mybatis.mapper-locations 指定的位置中创建 UserMapper.xml,代码如下。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.biancheng.www.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="User">
        <id column="id" jdbcType="INTEGER" property="id"/>
        <result column="user_id" jdbcType="VARCHAR" property="userId"/>
        <result column="user_name" jdbcType="VARCHAR" property="userName"/>
        <result column="password" jdbcType="VARCHAR" property="password"/>
        <result column="email" jdbcType="VARCHAR" property="email"/>
    </resultMap>
    <sql id="Base_Column_List">
        id, user_id, user_name, password, email
    </sql>
    <!--根据用户名密码查询用户信息-->
    <!--application.yml 中通过 type-aliases-package 指定了实体类的为了,因此-->
    <select id="getByUserNameAndPassword" resultType="User">
        select *
        from user
        where user_name = #{userName,jdbcType=VARCHAR}
          and password = #{password,jdbcType=VARCHAR}
    </select>
</mapper>

使用 Mapper 进行开发时,需要遵循以下规则:

  • mapper 映射文件中 namespace 必须与对应的 mapper 接口的完全限定名一致。
  • mapper 映射文件中 statement 的 id 必须与 mapper 接口中的方法的方法名一致
  • mapper 映射文件中 statement 的 parameterType 指定的类型必须与 mapper 接口中方法的参数类型一致。
  • mapper 映射文件中 statement 的 resultType 指定的类型必须与 mapper 接口中方法的返回值类型一致。

示例 1

  1. 在 spring-boot-adminex 项目中 net.biancheng.www.service 包中创建一个名为 UserService 的接口,代码如下。
package net.biancheng.www.service;
import net.biancheng.www.bean.User;
public interface UserService {
    public User getByUserNameAndPassword(User user);
}
  1. 在 net.biancheng.www.service.impl 包中创建 UserService 接口的实现类,并使用 @@Service 注解将其以组件的形式添加到容器中,代码如下。
package net.biancheng.www.service.impl;
import net.biancheng.www.bean.User;
import net.biancheng.www.mapper.UserMapper;
import net.biancheng.www.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public User getByUserNameAndPassword(User user) {
        User loginUser = userMapper.getByUserNameAndPassword(user);
        return loginUser;
    }
}
  1. 修改 LoginController 中的 doLogin() 方法 ,代码如下。
package net.biancheng.www.controller;
import lombok.extern.slf4j.Slf4j;
import net.biancheng.www.bean.User;
import net.biancheng.www.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Slf4j
@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping("/user/login")
    public String doLogin(User user, Map<String, Object> map, HttpSession session) {
        //从数据库中查询用户信息
        User loginUser = userService.getByUserNameAndPassword(user);
        if (loginUser != null) {
            session.setAttribute("loginUser", loginUser);
            log.info("登陆成功,用户名:" + loginUser.getUserName());
            //防止重复提交使用重定向
            return "redirect:/main.html";
        } else {
            map.put("msg", "用户名或密码错误");
            log.error("登陆失败");
            return "login";
        }
    }
}
  1. 启动 Spring Boot,浏览器地址栏输入“http://localhost:8080/” ,访问 AdminEx 系统的登陆页面,分别输入用户名“user”和密码“123456”,结果下图。

  1. 点击登陆按钮,结果如下图。

注解方式

通过上面的学习,我们知道 mapper 映射文件其实就是一个 XML 配置文件,它存在 XML 配置文件的通病,即编写繁琐,容易出错。即使是一个十分简单项目,涉及的 SQL 语句也都十分简单,我们仍然需要花费一定的时间在mapper 映射文件的配置上。

为了解决这个问题,MyBatis 针对实际实际业务中使用最多的“增伤改查”操作,分别提供了以下注解来替换 mapper 映射文件,简化配置:

  • @Select
  • @Insert
  • @Update
  • @Delete

通过以上注解,基本可以满足我们对数据库的增删改查操作,示例代码如下。

package net.biancheng.www.mapper;
import net.biancheng.www.bean.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
    @Select("select * from user where user_name = #{userName,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}")
    List<User> getByUserNameAndPassword(User user);
    @Delete("delete from user where id = #{id,jdbcType=INTEGER}")
    int deleteByPrimaryKey(Integer id);
    @Insert("insert into user ( user_id, user_name, password, email)" +
            "values ( #{userId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR})")
    int insert(User record);
    @Update(" update user" +
            "    set user_id = #{userId,jdbcType=VARCHAR},\n" +
            "      user_name = #{userName,jdbcType=VARCHAR},\n" +
            "      password = #{password,jdbcType=VARCHAR},\n" +
            "      email = #{email,jdbcType=VARCHAR}\n" +
            "    where id = #{id,jdbcType=INTEGER}")
    int updateByPrimaryKey(User record);
}

注意事项

mapper 接口中的任何一个方法,都只能使用一种配置方式,即注解和 mapper 映射文件二选一,但不同方法之间,这两种方式则可以混合使用,例如方法 1 使用注解方式,方法 2 使用 mapper 映射文件方式。

我们可以根据 SQL 的复杂程度,选择不同的方式来提高开发效率。

  • 如果没有复杂的连接查询,我们可以使用注解的方式来简化配置;
  • 如果涉及的 sql 较为复杂时,则使用 XML (mapper 映射文件)的方式更好一些。

Spring Boot自定义starter

starter 是 SpringBoot 中一种非常重要的机制,它可以繁杂的配置统一集成到 starter 中,我们只需要通过 maven 将 starter 依赖引入到项目中,SpringBoot 就能自动扫描并加载相应的默认配置。starter 的出现让开发人员从繁琐的框架配置中解放出来,将更多的精力专注于业务逻辑的开发,极大的提高了开发效率。

在一些特殊情况下,我们也可以将一些通用功能封装成自定义的 starter 进行使用,本节我们将为您详细介绍如何自定义 starter。

命名规范

SpringBoot 提供的 starter 以 spring-boot-starter-xxx 的形式命名。为了与 SpringBoot 生态提供的 starter 进行区分,官方建议第三方开发者或技术(例如 Druid、Mybatis 等等)厂商自定义的 starter 使用 xxx-spring-boot-starter 的形式命名,例如 mybatis-spring-boot-starter、druid-spring-boot-starter 等等。

模块规范

Spring Boot 官方建议我们在自定义 starter 时,创建两个 Module :autoConfigure Module 和 starter Module,其中 starter Module 依赖于 autoConfigure Module。当然,这只是 Spring Boot 官方的建议,并不是硬性规定,若不需要自动配置代码和依赖项目分离,我们也可以将它们组合到同一个 Module 里。

自定义 starter

自定义 starter 可以分为以下 7 步:

  1. 创建工程
  2. 添加 POM 依赖
  3. 定义 propertie 类
  4. 定义 Service 类
  5. 定义配置类
  6. 创建 spring.factories文件
  7. 构建 starter

创建工程

  1. 使用 IntelliJ IDEA 创建一个空项目(Empty Project),如下图。

  1. 在 Project Structure 界面,点击左上角的“+”按钮,选择“New Module”,新建一个名为 bianchengbang-hello-spring-boot-starter 的 Maven Module 和一个名为 bianchengbang-helllo-spring-boot-starter-autoconfiguration 的 Spring Boot Module,如下图。

添加 POM 依赖

在 bianchengbang-hello-spring-boot-starter 的 pom.xml 中添加以下代码,将 bianchengbang-helllo-spring-boot-starter-autoconfiguration 作为其依赖项。

<!--添加自动配置模块为其依赖-->
<dependencies>
    <dependency>
        <groupId>net.biacheng.www</groupId>
        <artifactId>bianchengbang-helllo-spring-boot-starter-autoconfiguration</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

定义 propertie 类

在 bianchengbang-helllo-spring-boot-starter-autoconfiguration 的 net.biacheng.www.properties 包中,创建一个实体类:HelloProperties,通过它来映射配置信息,其代码如下。

package net.biacheng.www.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 实体类,用来映射配置信息
*/
@ConfigurationProperties("net.biancheng.www.hello")
public class HelloProperties {
    private String prefix;
    private String suffix;
    public String getPrefix() {
        return prefix;
    }
    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    public String getSuffix() {
        return suffix;
    }
    public void setSuffix(String suffix) {
        this.suffix = suffix;
    }
}

HelloProperties 类上使用了 @ConfigurationProperties(“net.biancheng.www.hello"),其含义是将该类中的属性与配置文件中的以 net.biancheng.www.hello 开头的配置进行绑定。

定义 Service 类

在 bianchengbang-helllo-spring-boot-starter-autoconfiguration 的 net.biacheng.www.service 中,创建一个 Service 类:HelloService,供其他项目使用,代码如下。

package net.biacheng.www.service;
import net.biacheng.www.properties.HelloProperties;
import org.springframework.beans.factory.annotation.Autowired;
/**
* servcie 类,供外部调用
*/
public class HelloService {
    @Autowired
    HelloProperties helloProperties;
    public String sayHello(String userName) {
        return helloProperties.getPrefix() + userName + helloProperties.getSuffix();
    }
}

定义配置类

在 bianchengbang-helllo-spring-boot-starter-autoconfiguration 的 net.biacheng.www.autoConfiguration 中,创建一个配置类:HelloAutoConfiguration,其代码如下。

package net.biacheng.www.autoConfiguration;
import net.biacheng.www.properties.HelloProperties;
import net.biacheng.www.service.HelloService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(HelloProperties.class) //启用 HelloProperties,并默认将它添加到容器中
public class HelloAutoConfiguration {
    @ConditionalOnMissingBean(HelloService.class) //当容器中没有 HelloService 时生效
    @Bean
    public HelloService helloService() {
        HelloService helloService = new HelloService();
        return helloService;
    }
}

HelloAutoConfiguration 使用了以下 4 个注解:

  • @Configuration:表示该类是一个配置类;
  • @EnableConfigurationProperties(HelloProperties.class):该注解的作用是为 HelloProperties 开启属性配置功能,并将这个类以组件的形式注入到容器中;
  • @ConditionalOnMissingBean(HelloService.class):该注解表示当容器中没有 HelloService 类时,该方法才生效;
  • @Bean:该注解用于将方法的返回值以 Bean 对象的形式添加到容器中。

创建 spring.factories文件

由于 Spring Boot 的自动配置是基于 Spring Factories 机制实现的,因此我们自定义 starter 时,同样需要在项目类路径下创建一个 spring.factories 文件。

在 bianchengbang-helllo-spring-boot-starter-autoconfiguration 的类路径下(resources )中创建一个 META-INF 文件夹,并在 META-INF 文件夹中创建一个 spring.factories 文件,如下图。

将 Spring Boot 的 EnableAutoConfiguration 接口与自定义 starter 的自动配置类 HelloAutoConfiguration 组成一组键值对添加到 spring.factories 文件中,以方便 Spring Boot 在启动时,获取到自定义 starter 的自动配置,代码如下。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
net.biacheng.www.autoConfiguration.HelloAutoConfiguration

Spring Factories 机制是 Spring Boot 中的一种服务发现机制,这种机制与 Java SPI 机制十分相似。Spring Boot 会自动扫描所有 Jar 包类路径下 META-INF/spring.factories 文件,并读取其中的内容,进行实例化,这种机制也是 Spring Boot Starter 的基础。

Spring Factories 机制是 Spring Boot 中的一种服务发现机制,这种机制与 Java SPI 机制十分相似。Spring Boot 会自动扫描所有 Jar 包类路径下 META-INF/spring.factories 文件,并读取其中的内容,进行实例化,这种机制也是 Spring Boot Starter 的基础。

构建 starter

接下来,我们需要对自定义 starter 进行构建,并将它安装到本地仓库或远程仓库中,供其他项目使用。由于我们是在本地的项目中引用和测试,因此只需要使用 install 命令安装到本地仓库即可。

构建 autoConfigure Module

由于 starter Module 是依赖于 autoConfigure Module 的,因此我们需要先对 autoConfigure Module 进行构建。

在 bianchengbang-helllo-spring-boot-starter-autoconfiguration 的 pom.xml 中执行以下 mvn 命令,对它进行构建。

mvn clean install

命令执行结果如下。

[INFO] Scanning for projects...
[INFO]
[INFO] --< net.biacheng.www:bianchengbang-helllo-spring-boot-starter-autoconfiguration >--
[INFO] Building bianchengbang-helllo-spring-boot-starter-autoconfiguration 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Deleting D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 0 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-jar-plugin:3.2.0:jar (default-jar) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Building jar: D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Installing D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.jar to D:\myRepository\repository\net\biacheng\www\bianchengbang-helllo-spring-boot-starter-autoconfiguration\0.0.1-SNAPSHOT\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.jar
[INFO] Installing D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\pom.xml to D:\myRepository\repository\net\biacheng\www\bianchengbang-helllo-spring-boot-starter-autoconfiguration\0.0.1-SNAPSHOT\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.285 s
[INFO] Finished at: 2021-07-05T09:59:11+08:00
[INFO] ------------------------------------------------------------------------

构建 starter Module

在 autoConfigure Module 构建完成后,接下来我们就可以对 starter Module 进行构建,构建完成后,其他 Spring Boot 项目便可以引用该自定义 starter 了。

在 bianchengbang-hello-spring-boot-starter 的 pom.xml 中执行以下 mvn 命令,对它进行构建。

mvn clean install

命令执行结果如下。

[INFO] Scanning for projects...
[INFO]
[INFO] --< net.biacheng.www:bianchengbang-helllo-spring-boot-starter-autoconfiguration >--
[INFO] Building bianchengbang-helllo-spring-boot-starter-autoconfiguration 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.1.0:clean (default-clean) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Deleting D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 0 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target\classes
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] skip non existing resourceDirectory D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\src\test\resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-jar-plugin:3.2.0:jar (default-jar) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Building jar: D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ bianchengbang-helllo-spring-boot-starter-autoconfiguration ---
[INFO] Installing D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\target\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.jar to D:\myRepository\repository\net\biacheng\www\bianchengbang-helllo-spring-boot-starter-autoconfiguration\0.0.1-SNAPSHOT\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.jar
[INFO] Installing D:\IDEA\demo\spring-boot-my-starter\bianchengbang-helllo-spring-boot-starter-autoconfiguration\pom.xml to D:\myRepository\repository\net\biacheng\www\bianchengbang-helllo-spring-boot-starter-autoconfiguration\0.0.1-SNAPSHOT\bianchengbang-helllo-spring-boot-starter-autoconfiguration-0.0.1-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.257 s
[INFO] Finished at: 2021-07-05T10:06:44+08:00
[INFO] ------------------------------------------------------------------------

当引用自定义 starter 的项目不在本地时,我们需要使用 mvn 命令“mvn clean deploy”将自定义 starter 部署到远程仓库中。

测试

  1. 创建一个名为 test-my-starter 的 Spring Boot 项目,并在其 pom.xml 中引入依赖 bianchengbang-hello-spring-boot-starter(自定义 starter),代码如下。
<?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.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>net.biacheng.www</groupId>
    <artifactId>test-my-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test-my-starter</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--引入 web 功能的 starter-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--引入测试 starter-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--引入自定义 starter -->
        <dependency>
            <groupId>net.biancheng.www</groupId>
            <artifactId>bianchengbang-hello-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  1. 在 Spring Boot 配置文件 application.properties 中,添加以下属性配置。
#自定义 starter prefix 属性
net.biancheng.www.hello.prefix=你好: 
#自定义 starter suffix 属性
net.biancheng.www.hello.suffix=,欢迎您来到编程帮!
  1. 在 net.biancheng.www.controller 中创建一个控制器类 HelloController,代码如下。
package net.biacheng.www.controller;
import net.biacheng.www.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class HelloController {
    //自动装配自定义 starter 的 service
    @Autowired
    HelloService helloService;
    @ResponseBody
    @GetMapping("/hello")
    public String SayHello(String name) {
        return helloService.sayHello(name);
    }
}
  1. 启动 Spring Boot,使用浏览器访问“http://localhost:8080/hello?name=小明”,结果如下图。

可以看到,我们自定义的 starter 已经生效。

SpringBoot服务部署

环境配置

  • 在服务器上安装配置号Java的JDK环境

  • Java环境配置这里就不再过多赘述

打包项目运行

  • 用IDEL打开项目,使用maven导出jar包

  • jar包打包完毕,看到下图构建成功

  • target目录下生成jar包,将第一个上传到服务器

  • 在服务器启动jar包
java -jar xxxx.jar
  • 如果启动报no main manifest attribute,在本地的pom.xml中加入,注意这个添加在project标签内,然后重新打包上传运行即可
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

Spring Boot开发实战


文章作者: 杰克成
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 杰克成 !
评论
  目录