51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

【WEB 系列】SpirngBoot 整合 Swagger

背景 {#背景}

由于 Spring Boot 能够快速开发、便捷部署等特性,相信有很大一部分 Spring Boot 的用户会用来构建 RESTful API。而我们构建 RESTful API 的目的通常都是由于多终端的原因,这些终端会共用很多底层业务逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者 Web 前端。

​ 这样一来,我们的 RESTful API 就有可能要面对多个开发人员或多个开发团队:IOS 开发、Android 开发或是 Web 开发等。为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份 RESTful API 文档来记录所有接口细节,然而这样的做法有以下几个问题:

  • 由于接口众多,并且细节复杂(需要考虑不同的 HTTP 请求类型、HTTP 头部信息、HTTP 请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下游的抱怨声不绝于耳。
  • 随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象。

​ 为了解决上面这样的问题,本文将介绍 RESTful API 的重磅好伙伴 Swagger2,它可以轻松的整合到 Spring Boot 中,并与 Spring MVC 程序配合组织出强大 RESTful API 文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外 Swagger2 也提供了强大的页面测试功能来调试每个 RESTful API。

前后端分离缺陷 {#前后端分离缺陷}

了解 Swagger 之前, 需要先知道什么是前后端分离

  • 现在的时代
    • SpringBoot + VUE
  • 以前的时代
    • SSM + JSP 模板引擎 ====> 后端程序员
  • 前后端分离时代
    • 后端: 后端控制层 + 服务层 + 数据访问层
    • 前端: 前端控制层 + 视图层
      • 伪造后端交互数据,json 数据已经存在, 不需要后端传入 json 数据了, 前端工程已经可以运行
    • 前后端如何交互?
      • 通过相关的 API 接口进行交互
      • 前后端相对独立, 松耦合
      • 前后端可以分别部署在不同的服务器上
  • 但这样会产生新问题
    • 前后端集成联调, 前端和后端开发人员无法做到 及时协商, 尽早解决问题, 就会导致项目延期
  • 解决方案:
    • 首先指定 schema[计划大纲], 团队实时更新最新的 API, 可以降低集成的风险;
    • 早些年: 指定 world 计划文档
    • 前后端分离:
      • 前端测试后端:postMan
      • 后端提供接口, 需要实时更新最新的消息和改动

Swagger 简介 {#Swagger 简介}

Swagger 官网

  • 号称世界上最流行的 API 框架
  • RestFul API 文档在线生成工具--->>>==API 文档与 API 同步更新 ==
  • 可以直接运行, 可以在线测试 API 接口
  • 支持多种语言:(Java,PHP)

官网界面

Swagger 是一款 RESTFUL 接口的文档在线自动生成 + 功能测试功能软件。本文简单介绍了在项目中集成 swagger 的方法和一些常见问题。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

使用 SpringBoot 集成 Swagger {#使用 SpringBoot 集成 Swagger}

  • 创建 SpringBoot-Web 项目, 导入相关依赖

注意事项:

  • 在项目中使用 Swagger 需要 SpringBox
  • swagger2
  • swaggerui
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
  • 创建 hello 程序

扩展, 一个 hello 程序有两个请求, 一个是 SpringBoot 项目默认的/error

@RestController
public class HelloController {
    /**
     * 测试 Controller
     *
     * @return
     */
    @GetMapping("/hello")
    public String hello() {
        return "你好呀!!!Swagger";
    }
}
  • 配置Swagger, 新建SwaggerConfig
@Configuration // 标识配置类
@EnableSwagger2 // 开启 Swagger
public class SwaggerConfig {
}

  • 测试运行

唯一地址:http://localhost:8080/swagger-ui.html

首页信息

配置 Swagger 信息 {#配置 Swagger 信息}

  • 修改SwaagerConfig
package com.mobai.swagger.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


import java.util.ArrayList;


/**




* 
  Software:IntelliJ IDEA 2020.1 x64





* 
  Author: MoBai·杰





* 
  Date: 2020/6/11 13:33





* 
  ClassName:SwaggerConfig





* 
  类描述: Swagger 配置类
  \*/
  @Configuration // 标识配置类
  @EnableSwagger2 // 开启 Swagger
  public class SwaggerConfig {



  /**



  * 配置了 Swagger 的 Docket 的 Bean 实例


  * 


  * @return
    */
    @Bean
    public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }




  /**



  * 配置 Swagger 信息


  * 


  * @return
    */
    private ApiInfo apiInfo() {
    // 配置作者信息
    Contact contact = new Contact("墨白",
    "https://www.mobaijun.com",
    "mobaijun8@163.com");
    // 配置 API 文档标题
    return new ApiInfo("框架师 Api",
    // API 文档描述
    "Api Documentation",
    // API 版本号
    "1.0",
    // 配置 URL(公司官网 /blog 地址)
    "https://www.mobaijun.com",
    // 作者信息
    contact,
    // 以下内容默认即可
    "Apache 2.0",
    "http://www.apache.org/licenses/LICENSE-2.0",
    new ArrayList());
    }





}

Swagger 配置扫描接口 {#Swagger 配置扫描接口}

Docket.select();

  • SawggerConfig 配置类完善配置扫描接口的参数
/**
 * 配置了 Swagger 的 Docket 的 Bean 实例
 *
 * @return
 */
@Bean
public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            // 配置扫描接口
            .select()
            /*
             *RequestHandlerSelectors, 配置要扫描接口的方式
             * 参数说明:
             * basePackage: 基于包扫描
             * class: 基于类扫描
             * any(): 扫描全部
             * none(): 全部都不扫描
             * withMethodAnnotation: 通过方法的注解扫描
             * // withMethodAnnotation(GetMapping.class))
             * withClassAnnotation: 通过类的注解扫描
             */
          .apis(RequestHandlerSelectors.basePackage("com.mobai.swagger.controller"))
            // .paths()过滤, 不扫描哪些接口
            .paths(PathSelectors.any())
            .build();
}
  • 配置 Swagger 启动
/**
 * 配置了 Swagger 的 Docket 的 Bean 实例
 *
 * @return
 */
@Bean
public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            // 配置 Swagger 是否启动, 默认:true
            .enable(false)
            // 配置扫描接口
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.mobai.swagger.controller"))
            .paths(PathSelectors.any())
            .build();
}

小测试: 如果有一个需求, 需要你判断在生成环境中使用, 在发布的时候不使用

  • 开发思路
    • 先判断.enable()是不是等于false
    • 注入 Enable(flag)
  • 实现, 添加application-dev.properties 生产环境配置和 application-pro.properties 发布环境配置

  • 默认 application.properties 环境配置添加

# 开启 profiles.active 监听,dev 测试环境,pro 发布环境
spring.profiles.active=dev
  • 生产环境修改端口号
server.port=8081
  • 发布环境修改端口号
server.port=8082
  • SwaggerConfig配置类判断当前环境
/**
 * 配置了 Swagger 的 Docket 的 Bean 实例
 *
 * @return
 */
@Bean
public Docket docket(Environment environment) {
    // 设置要显示的 Swagger 环境
    Profiles profiles = Profiles.of("dev", "test");
    // 通过 environment.acceptsProfiles(); 判断自己是否在自己设定换的环境当中
    boolean flag = environment.acceptsProfiles(profiles);

    <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Docket</span><span class="token punctuation">(</span><span class="token class-name">DocumentationType</span><span class="token punctuation">.</span><span class="token constant">SWAGGER_2</span><span class="token punctuation">)</span>
            <span class="token punctuation">.</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
            <span class="token comment">// 监听自己设置的环境</span>
            <span class="token punctuation">.</span><span class="token function">enable</span><span class="token punctuation">(</span>flag<span class="token punctuation">)</span>
            <span class="token comment">// 配置扫描接口</span>
            <span class="token punctuation">.</span><span class="token function">select</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
            <span class="token punctuation">.</span><span class="token function">apis</span><span class="token punctuation">(</span><span class="token class-name">RequestHandlerSelectors</span><span class="token punctuation">.</span><span class="token function">basePackage</span><span class="token punctuation">(</span><span class="token string">"com.mobai.swagger.controller"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
            <span class="token punctuation">.</span><span class="token function">paths</span><span class="token punctuation">(</span><span class="token class-name">PathSelectors</span><span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
            <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>



}

配置 API 文档的分组 {#配置 API 文档的分组}

  • 配置多个组, 添加.groupName()
   /**
     * 配置了 Swagger 的 Docket 的 Bean 实例
     *
     * @return
     */
    @Bean
    public Docket docket(Environment environment) {
        // 设置要显示的 Swagger 环境
        Profiles profiles = Profiles.of("dev", "test");
        // 通过 environment.acceptsProfiles(); 判断自己是否在自己设定换的环境当中
        boolean flag = environment.acceptsProfiles(profiles);

        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Docket</span><span class="token punctuation">(</span><span class="token class-name">DocumentationType</span><span class="token punctuation">.</span><span class="token constant">SWAGGER_2</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token comment">// 配置分组</span>
                <span class="token punctuation">.</span><span class="token function">groupName</span><span class="token punctuation">(</span><span class="token string">"墨白小组"</span><span class="token punctuation">)</span>
                <span class="token comment">// 监听自己设置的环境</span>
                <span class="token punctuation">.</span><span class="token function">enable</span><span class="token punctuation">(</span>flag<span class="token punctuation">)</span>
                <span class="token comment">// 配置扫描接口</span>
                <span class="token punctuation">.</span><span class="token function">select</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">apis</span><span class="token punctuation">(</span><span class="token class-name">RequestHandlerSelectors</span><span class="token punctuation">.</span><span class="token function">basePackage</span><span class="token punctuation">(</span><span class="token string">"com.mobai.swagger.controller"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">paths</span><span class="token punctuation">(</span><span class="token class-name">PathSelectors</span><span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>



}

  • 效果

  • 配置多个组
@Configuration // 标识配置类
@EnableSwagger2 // 开启 Swagger
public class SwaggerConfig {

    <span class="token comment">/**
     * 添加 A 组
     * 每个组各司其职
     *
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Docket</span> <span class="token function">docket1</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Docket</span><span class="token punctuation">(</span><span class="token class-name">DocumentationType</span><span class="token punctuation">.</span><span class="token constant">SWAGGER_2</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">groupName</span><span class="token punctuation">(</span><span class="token string">"A"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 添加 B 组
     *
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Docket</span> <span class="token function">docket2</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Docket</span><span class="token punctuation">(</span><span class="token class-name">DocumentationType</span><span class="token punctuation">.</span><span class="token constant">SWAGGER_2</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">groupName</span><span class="token punctuation">(</span><span class="token string">"B"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 添加 C 组
     *
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Docket</span> <span class="token function">docket3</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Docket</span><span class="token punctuation">(</span><span class="token class-name">DocumentationType</span><span class="token punctuation">.</span><span class="token constant">SWAGGER_2</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">groupName</span><span class="token punctuation">(</span><span class="token string">"C"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment">/**
     * 配置了 Swagger 的 Docket 的 Bean 实例
     *
     * @return
     */</span>
    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Docket</span> <span class="token function">docket</span><span class="token punctuation">(</span><span class="token class-name">Environment</span> environment<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 设置要显示的 Swagger 环境</span>
        <span class="token class-name">Profiles</span> profiles <span class="token operator">=</span> <span class="token class-name">Profiles</span><span class="token punctuation">.</span><span class="token function">of</span><span class="token punctuation">(</span><span class="token string">"dev"</span><span class="token punctuation">,</span> <span class="token string">"test"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 通过 environment.acceptsProfiles(); 判断自己是否在自己设定换的环境当中</span>
        <span class="token keyword">boolean</span> flag <span class="token operator">=</span> environment<span class="token punctuation">.</span><span class="token function">acceptsProfiles</span><span class="token punctuation">(</span>profiles<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Docket</span><span class="token punctuation">(</span><span class="token class-name">DocumentationType</span><span class="token punctuation">.</span><span class="token constant">SWAGGER_2</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token comment">// 配置分组</span>
                <span class="token punctuation">.</span><span class="token function">groupName</span><span class="token punctuation">(</span><span class="token string">"墨白小组"</span><span class="token punctuation">)</span>
                <span class="token comment">// 监听自己设置的环境</span>
                <span class="token punctuation">.</span><span class="token function">enable</span><span class="token punctuation">(</span>flag<span class="token punctuation">)</span>
                <span class="token comment">// 配置扫描接口</span>
                <span class="token punctuation">.</span><span class="token function">select</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">apis</span><span class="token punctuation">(</span><span class="token class-name">RequestHandlerSelectors</span><span class="token punctuation">.</span><span class="token function">basePackage</span><span class="token punctuation">(</span><span class="token string">"com.mobai.swagger.controller"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">paths</span><span class="token punctuation">(</span><span class="token class-name">PathSelectors</span><span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



 

  
* 效果

 

 
![](http://static.51tbox.com/static/2025-01-10/col/274e63e9aacf52aaa1126b89ca0346fa/0368666a86a8482d99d4e059881b9be9.gif.jpg)

 

  
* 实体类配置

 

 
```java
@ApiModel("用户实体类") // 添加注释
public class User {
    // 添加注释
    @ApiModelProperty("年龄")
    private Integer age;

    <span class="token annotation punctuation">@ApiModelProperty</span><span class="token punctuation">(</span><span class="token string">"姓名"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> name<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@ApiModelProperty</span><span class="token punctuation">(</span><span class="token string">"账号"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> username<span class="token punctuation">;</span>

    <span class="token annotation punctuation">@ApiModelProperty</span><span class="token punctuation">(</span><span class="token string">"密码"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token class-name">String</span> password<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token class-name">Integer</span> <span class="token function">getAge</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> age<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setAge</span><span class="token punctuation">(</span><span class="token class-name">Integer</span> age<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>age <span class="token operator">=</span> age<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> name<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setName</span><span class="token punctuation">(</span><span class="token class-name">String</span> name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getUsername</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> username<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setUsername</span><span class="token punctuation">(</span><span class="token class-name">String</span> username<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>username <span class="token operator">=</span> username<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getPassword</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> password<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setPassword</span><span class="token punctuation">(</span><span class="token class-name">String</span> password<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>password <span class="token operator">=</span> password<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>



}

```


<br />



 

  
* 效果

 

 
![效果图](http://static.51tbox.com/static/2025-01-10/col/274e63e9aacf52aaa1126b89ca0346fa/0368666a86a8482d99d4e059881b9be9.gif.jpg)

 

  
* Swagger 常用注解


     
      
  * `@ApiModel(" 注释 ")`: 实体类添加注释

      
  * `@ApiModelProperty(" 注释 ")`: 给实体类属性添加注释

      
  * `@ApiOperation(" 注释 ")`给接口 (Controller) 方法添加注释, 放在方法上

      
  * `@ApiParam("")`给方法的参数添加注释

      
  * `@Api("")`给类添加注释

     

  
* controller



 

 
```java
package com.mobai.swagger.controller;

import com.mobai.swagger.pojo.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


/**

`
`
* 
  Software:IntelliJ IDEA 2020.1 x64





* 
  Author: MoBai·杰





* 
  Date: 2020/6/11 13:25





* 
  ClassName:HelloController






* `
  `类描述: 测试类
  /
  @ApiOperation("")
  @RestController
  public class HelloController {
  /*
  `
  `

  * 测试 Controller


  * 


  * @return
    */
    @GetMapping("/hello")
    public String hello() {
    return "不喜欢你啦你好呀!!!Swagger";
    }


  `
  `

  /**
  `
  `

  * 只要我们的接口中, 返回值存在实体类,Swagger 就会扫描到


  * 


  * @return
    */
    @PostMapping("/user")
    public User user() {
    return new User();
    }

  `
  `

  @ApiOperation("Post 测试类")`
  `@PostMapping(`value `=` `"/post")`
  `public` `User` `post(@ApiParam("用户对象")` `User` user`)` `{`
  `return` user`;`
  `}`
  `}


```


<br />





 
Springboot 项目集成 Swagger2 {#Springboot- 项目集成 -Swagger2}
------------------------------------------------------


 
### 1、Maven 引入 Swagger2 依赖 {#1、Maven- 引入 -Swagger2- 依赖}


 
新建 Maven 项目,往其 pom.xml 中引入 Springboot 及 Swagger 相关 Jar。

 
```markup
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">&gt;</span></span>com.mobai<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">&gt;</span></span>swagger-example-service<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">&gt;</span></span>1.0.0<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>name</span><span class="token punctuation">&gt;</span></span>swagger-example-service<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>name</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>description</span><span class="token punctuation">&gt;</span></span>springboot swagger api example service<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>description</span><span class="token punctuation">&gt;</span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>properties</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>java.version</span><span class="token punctuation">&gt;</span></span>1.8<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>java.version</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>properties</span><span class="token punctuation">&gt;</span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependencies</span><span class="token punctuation">&gt;</span></span>
        <span class="token comment">&lt;!-- SpringBoot Web --&gt;</span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">&gt;</span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">&gt;</span></span>spring-boot-starter-web<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">&gt;</span></span>2.1.5.RELEASE<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">&gt;</span></span>
        <span class="token comment">&lt;!-- 引入 Lombok,方便开发 --&gt;</span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">&gt;</span></span>org.projectlombok<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">&gt;</span></span>lombok<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">&gt;</span></span>1.18.8<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>scope</span><span class="token punctuation">&gt;</span></span>provided<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>scope</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">&gt;</span></span>
        <span class="token comment">&lt;!-- 引入 Swagger 相关依赖 --&gt;</span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">&gt;</span></span>io.springfox<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">&gt;</span></span>springfox-swagger2<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">&gt;</span></span>2.9.2<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>dependency</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">&gt;</span></span>io.springfox<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">&gt;</span></span>springfox-swagger-ui<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>version</span><span class="token punctuation">&gt;</span></span>2.9.2<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>version</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependency</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>dependencies</span><span class="token punctuation">&gt;</span></span>

    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>build</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>plugins</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>plugin</span><span class="token punctuation">&gt;</span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>groupId</span><span class="token punctuation">&gt;</span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>groupId</span><span class="token punctuation">&gt;</span></span>
                <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>artifactId</span><span class="token punctuation">&gt;</span></span>spring-boot-maven-plugin<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>artifactId</span><span class="token punctuation">&gt;</span></span>
            <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>plugin</span><span class="token punctuation">&gt;</span></span>
        <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>plugins</span><span class="token punctuation">&gt;</span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>build</span><span class="token punctuation">&gt;</span></span>



</project>

```


<br />



 
### 2、创建 Swagger 配置类 {#2、创建 -Swagger- 配置类}


 
创建 Swagger 配置类,设置 Swagger 文档信息, 在 Swagger 配置类上加上 @EnableSwagger2 注解以开启 Swagger2。

 
>   注意:配置中不要设置 "groupName" 参数,否则可能无法文档聚合。也可以使用更加优雅的注解读取方式来配置相关参数!
>
>  

 
```java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@EnableSwagger2  // 开启 Swagger
@Configuration
public class SwaggerConfig {


    <span class="token annotation punctuation">@Value</span><span class="token punctuation">(</span><span class="token string">"${swagger.enable}"</span><span class="token punctuation">)</span>
    <span class="token keyword">private</span> <span class="token keyword">boolean</span> swaggerEnable<span class="token punctuation">;</span>  <span class="token comment">// 读取配置文件中 swagger 开关参数的值</span>

    <span class="token annotation punctuation">@Bean</span>
    <span class="token keyword">public</span> <span class="token class-name">Docket</span> <span class="token function">createRestApi</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Docket</span><span class="token punctuation">(</span><span class="token class-name">DocumentationType</span><span class="token punctuation">.</span><span class="token constant">SWAGGER_2</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">enable</span><span class="token punctuation">(</span>swaggerEnable<span class="token punctuation">)</span>                  <span class="token comment">// 是否启用 Swagger</span>
                <span class="token punctuation">.</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
                <span class="token comment">//.groupName("swagger-example-service") // 项目组名</span>
                <span class="token punctuation">.</span><span class="token function">select</span><span class="token punctuation">(</span><span class="token punctuation">)</span>                               <span class="token comment">// 选择那些路径和 api 会生成 document</span>
                <span class="token punctuation">.</span><span class="token function">apis</span><span class="token punctuation">(</span><span class="token class-name">RequestHandlerSelectors</span><span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>    <span class="token comment">// 对所有 api 进行监控</span>
                <span class="token punctuation">.</span><span class="token function">paths</span><span class="token punctuation">(</span><span class="token class-name">PathSelectors</span><span class="token punctuation">.</span><span class="token function">any</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>             <span class="token comment">// 对所有路径进行监控</span>
                <span class="token punctuation">.</span><span class="token function">paths</span><span class="token punctuation">(</span><span class="token class-name">Predicates</span><span class="token punctuation">.</span><span class="token function">not</span><span class="token punctuation">(</span><span class="token class-name">PathSelectors</span><span class="token punctuation">.</span><span class="token function">regex</span><span class="token punctuation">(</span><span class="token string">"/error.*"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment">// 错误路径不监控</span>
                <span class="token punctuation">.</span><span class="token function">paths</span><span class="token punctuation">(</span><span class="token class-name">Predicates</span><span class="token punctuation">.</span><span class="token function">not</span><span class="token punctuation">(</span><span class="token class-name">PathSelectors</span><span class="token punctuation">.</span><span class="token function">regex</span><span class="token punctuation">(</span><span class="token string">"/actuator.*"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment">//actuator 路径跳过</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token class-name">ApiInfo</span> <span class="token function">apiInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ApiInfoBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
                <span class="token punctuation">.</span><span class="token function">title</span><span class="token punctuation">(</span><span class="token string">"swagger-example-service"</span><span class="token punctuation">)</span>           <span class="token comment">// 文档标题</span>
                <span class="token punctuation">.</span><span class="token function">description</span><span class="token punctuation">(</span><span class="token string">"This is a swagger project."</span><span class="token punctuation">)</span>  <span class="token comment">// 文档描述</span>
                <span class="token punctuation">.</span><span class="token function">version</span><span class="token punctuation">(</span><span class="token string">"1.0.0"</span><span class="token punctuation">)</span>                           <span class="token comment">// 文档版本</span>
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>



}

```


<br />



 
### 3、配置文件中添加 swagger 开关参数 {#3、配置文件中添加 -swagger- 开关参数}


 
配置文件 application.yml 中添加 `swagger.enable` 配置参数,方便控制是否开启 `swagger`,一般在生产环境中我们会设置这个值为 `false`。

 
```yaml
spring:
  application:
    name: swagger-example-service
### Swagger 开关配置参数`
`swagger:`
`enable:` `true

```


<br />



 
### 4、创建 user 实体类 {#4、创建 -user- 实体类}


 
为了方便测试,这里创建一个 User 实体类,并且利用 Swagger 的 @ApiModelProperty 注解对实体类某个属性描述,方便 Swagger 文档中描述实体类中信息。

 
```java
import io.swagger.annotations.ApiModelProperty;
import java.util.Date;
public` `class` `User` `{`
`// @ApiModelProperty:用于描述字段信息`
`@ApiModelProperty(`value `=` `"姓名",` required `=` `true)`
`private` `String` name`;`
`@ApiModelProperty(`value `=` `"性别",` required `=` `true)`
`private` `String` sex`;`
`@ApiModelProperty(`value `=` `"岁数",` required `=` `true)`
`private` `Integer` age`;`
`@ApiModelProperty(`value `=` `"生日")`
`private` `Date` birthday`;`
`}

```


<br />



 
### 5、创建示例 Controller 接口 {#5、创建示例 -Controller- 接口}


 
创建一个 Controller 类,且运用 Swagger 注解,将接口信息详细描述。

 
这里用了几个 Swagger 注解,分别为:

 

  
* @Api:对整个 Controller 接口信息的描述

  
* @ApiOperation:对某个接口信息进行描述

  
* @ApiResponses:对某个反馈信息状态码进行描述

  
* @ApiParam:对某个接口参数进行描述

 

 
```java
import io.swagger.annotations.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(tags = "Example Controller Document")
public class ExampleController {


    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/example"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiOperation</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"获取示例信息"</span><span class="token punctuation">,</span> notes <span class="token operator">=</span> <span class="token string">"用 Get 请求发送,获取示例设置的字符串信息。"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiResponses</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">200</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"成功处理请求"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">401</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"没有权限访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">403</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"权限不足无法访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">404</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"未发现该微服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">500</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"服务器内部错误"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">String</span> <span class="token function">getExample</span><span class="token punctuation">(</span>
            <span class="token annotation punctuation">@ApiParam</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"输入一个 Key"</span><span class="token punctuation">)</span> <span class="token annotation punctuation">@RequestParam</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"key"</span><span class="token punctuation">)</span> <span class="token class-name">String</span> key<span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiParam</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"输入一个 Value"</span><span class="token punctuation">,</span> required <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token annotation punctuation">@RequestParam</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"value"</span><span class="token punctuation">)</span> <span class="token class-name">String</span> value<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"The value you enter is:"</span> <span class="token operator">+</span> key <span class="token operator">+</span> <span class="token string">":"</span> <span class="token operator">+</span> value<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@PostMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/example"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiOperation</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"发送示例信息"</span><span class="token punctuation">,</span> notes <span class="token operator">=</span> <span class="token string">"Post 方法,发送示例信息"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiResponses</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">200</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"成功处理请求"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">401</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"没有权限访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">403</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"权限不足无法访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">404</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"未发现该微服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">500</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"服务器内部错误"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">ResponseEntity</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">User</span><span class="token punctuation">&gt;</span></span> <span class="token function">postExample</span><span class="token punctuation">(</span><span class="token annotation punctuation">@ApiParam</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"用户信息"</span><span class="token punctuation">)</span> <span class="token annotation punctuation">@RequestBody</span> <span class="token class-name">User</span> user<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 设置状态码,且设置默认值为 200</span>
        <span class="token class-name">HttpStatus</span> httpStatus <span class="token operator">=</span> <span class="token class-name">HttpStatus</span><span class="token punctuation">.</span><span class="token constant">OK</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ResponseEntity</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">User</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span>user<span class="token punctuation">,</span>httpStatus<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@PutMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/example"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiResponses</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">200</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"成功处理请求"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">201</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"被创建"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">401</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"没有权限访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">403</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"权限不足无法访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">404</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"未发现该微服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">500</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"服务器内部错误"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiOperation</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"修改示例信息"</span><span class="token punctuation">,</span> notes <span class="token operator">=</span> <span class="token string">"Put 方法,修改示例信息"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token class-name">ResponseEntity</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">User</span><span class="token punctuation">&gt;</span></span> <span class="token function">putExample</span><span class="token punctuation">(</span><span class="token annotation punctuation">@ApiParam</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"用户信息"</span><span class="token punctuation">)</span> <span class="token annotation punctuation">@RequestBody</span> <span class="token class-name">User</span> user<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token comment">// 设置状态码,且设置默认值为 200</span>
        <span class="token class-name">HttpStatus</span> httpStatus <span class="token operator">=</span> <span class="token class-name">HttpStatus</span><span class="token punctuation">.</span><span class="token constant">OK</span><span class="token punctuation">;</span>
        <span class="token comment">// 设置 Headers</span>
        <span class="token class-name">HttpHeaders</span> httpHeaders <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HttpHeaders</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        httpHeaders<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token class-name">HttpHeaders</span><span class="token punctuation">.</span><span class="token constant">CONTENT_TYPE</span><span class="token punctuation">,</span> <span class="token class-name">MimeTypeUtils</span><span class="token punctuation">.</span><span class="token constant">APPLICATION_JSON_VALUE</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 错误就发送 500 错误</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>user <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            httpStatus <span class="token operator">=</span> <span class="token class-name">HttpStatus</span><span class="token punctuation">.</span><span class="token constant">INTERNAL_SERVER_ERROR</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">ResponseEntity</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">User</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span>user<span class="token punctuation">,</span> httpHeaders<span class="token punctuation">,</span> httpStatus<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@DeleteMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/example/{key}"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiOperation</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"删除示例信息"</span><span class="token punctuation">,</span> notes <span class="token operator">=</span> <span class="token string">"Delete 方法,删除示例信息。"</span><span class="token punctuation">)</span>
    <span class="token annotation punctuation">@ApiResponses</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">200</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"成功处理请求"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">204</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"成功处理请求,服务器无返回内容"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">401</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"没有权限访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">403</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"权限不足无法访问该服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">404</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"未发现该微服务"</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token annotation punctuation">@ApiResponse</span><span class="token punctuation">(</span>code <span class="token operator">=</span> <span class="token number">500</span><span class="token punctuation">,</span> message <span class="token operator">=</span> <span class="token string">"服务器内部错误"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">deleteExample</span><span class="token punctuation">(</span><span class="token annotation punctuation">@ApiParam</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"输入一个 Key"</span><span class="token punctuation">)</span> <span class="token annotation punctuation">@PathVariable</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"key"</span><span class="token punctuation">)</span> <span class="token class-name">String</span> key<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"delete info"</span> <span class="token operator">+</span> key<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>



}

```


<br />



 
### 6、启动类 {#6、启动类}


 
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
public class Application {


    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token class-name">SpringApplication</span><span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span><span class="token class-name">Application</span><span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">,</span> args<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>



}

```


<br />



 
### 7、访问 Swagger API {#7、访问 -Swagger-API}


 
项目创建完成后,本地启动然后输入地址 http://localhost:8080/v2/api-docs%EF%BC%8C%E5%8F%AF%E4%BB%A5%E7%9C%8B%E8%A7%81 Swagger API 接口返回的 JSON 信息。

 
```json
{
    "swagger": "2.0",
    "info": {
        "description": "This is a swagger project.",
        "version": "1.0.0",
        "title": "swagger-example-service"
    },
    "host": "localhost:8080",
    "basePath": "/",
    "tags": [
        {
            "name": "Example Controller Doc",
            "description": "Example Controller"
        },
        {
            "name": "basic-error-controller",
            "description": "Basic Error Controller"
        }
    ],
    "paths": {
        "/error": {
            "get": {
                "tags": [
                    "basic-error-controller"
                ],
                "summary": "error",
                "operationId": "errorUsingGET",
                "produces": [
                    "*/*"
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "schema": {
                            "type": "object",
                            "additionalProperties": {
                                "type": "object"
                            }
                        }
                    },
                    "401": {
                        "description": "Unauthorized"
                    },
                    "403": {
                        "description": "Forbidden"
                    },
                    "404": {
                        "description": "Not Found"
                    }
                }

```


 
### 8、访问 Swagger UI {#8、访问 -Swagger-UI}


 
Swagger 除了有 Json 形式的数据外,也有对 Json 数据页面化展示的 Swagger UI,在开始的时候 pom.xml 就已经引入该 Swagger UI 相关 Jar,所以这里我们将项目启动后,输入地址 http://localhost:8080/swagger-ui.html 就能访问到 Swagger 接口信息。

 
![测试](http://static.51tbox.com/static/2025-01-10/col/274e63e9aacf52aaa1126b89ca0346fa/0368666a86a8482d99d4e059881b9be9.gif.jpg)

 

  
* 总结 
     
      
  * 创建 SpringBoot 项目, 导入 `Swagger` 依赖 
         
          
    * `Swagger2`

          
    * `Swagger-ui`

         

      
  * 创建 `Swagger` 配置类 
         
          
    * 添加 `@Configuration` 注解, 标识配置类

          
    * 添加 `@EnableSwagger2` 注解开启 Swagger

         

      
  * 配置 `Swagger` 的`Docket`的 `Bean` 实例

      
  * 配置 `Swagger` 信息

     

  
* 我们可以通过 Swagger 给一些比较难理解的属性或者接口, 增加注释信息

  
* 接口文档实时更新

  
* 可以在线测试

  
* Swagger 是一个优秀的工具, 几乎所有的大公司都在用

  
* 需要注意 : 正式发布的时候, 关闭 swagger!!! 出于安全考虑, 而且节省运行内存!

 

赞(0)
未经允许不得转载:工具盒子 » 【WEB 系列】SpirngBoot 整合 Swagger