Spring Boot 集成 Swagger 2.0 生成 API 文档

本文介绍 Spring Boot 2 集成 SpringFox Swagger2 生成 API 文档的方法。


目录

  • SpringFox Swagger2 简介
  • 常用注解
    • @Api
    • @ApiModel
    • @ApiModelProperty
    • @ApiOperation
    • @ApiParam
    • @ApiImplicitParam
    • @ApiImplicitParams
    • @ApiResponse
    • @ApiResponses
    • @ResponseHeader
  • 开发环境
  • 基础示例
  • 总结

SpringFox Swagger2 简介

SpringFox 用于在 Spring 应用中自动化构建 API 文档。
Swagger2 是一款功能强大的 API 构建工具。


常用注解

@Api

修饰类,说明该类的用途,与 @Controller 注解一起使用。
注解属性说明:

  • value:URL 路径。
  • tags:如果设置则会覆盖 value 的值。
  • description:对 API 资源的描述。
  • basePath:基本路径,可以不配置。
  • position:如果配置了多个 API,可以据此修改显示的顺序和位置。
  • producesapplication/jsonapplication/xml 等。
  • consumesapplication/jsonapplication/xml 等。
  • protocolshttphttpswswss 等。
  • authorizations:高级特性认证时配置。
  • hidden:如果配置为 true 则在文档中会隐藏。
@ApiModel

修饰模型类,一般用于使用 @RequestBody 传参的场景,因为这类请求参数无法使用 @ApiImplicitParam 注解进行描述。

@ApiModelProperty

修饰模型类的属性。

@ApiOperation

修饰 Controller 中的方法,定义每一个 URL 资源,描述针对特定路径的操作,通常是 HTTP 方法。
注解属性说明:

  • value:URL 路径。
  • tags:如果设置则会覆盖 value 的值。
  • description:对 API 资源的描述。
  • basePath:基本路径,可以不配置。
  • position:如果配置了多个 API,可以据此修改显示的顺序和位置。
  • producesapplication/jsonapplication/xml 等。
  • consumesapplication/jsonapplication/xml 等。
  • protocolshttphttpswswss 等。
  • authorizations:高级特性认证时配置。
  • hidden:如果配置为 true 则在文档中会隐藏。
  • response:返回的对象。
  • responseContainer:返回对象的容器,仅对 ListSetMapArray 有效。
  • httpMethodGETHEADPOSTPUTDELETEOPTIONSPATCH
  • code:HTTP 状态码,默认为 200
  • extensions:扩展属性。
@ApiParam

修饰 Controller 中方法的属性,为参数添加额外元数据,此注解只能与 JAX-RS 1.x / 2.x 注解组合使用。
注解属性说明:

  • name:属性名称。
  • value:属性值。
  • defaultValue:默认属性值。
  • allowableValues:属性有效范围。
  • required:是否必填。
  • access
  • allowMultiple:默认为 false
  • hidden:如果配置为 true 则在文档中会隐藏。
  • example:示例。
@ApiImplicitParam

修饰 Controller 中的方法,也可用在 @ApiImplicitParams 注解中,描述 API 接口中的单个参数。
注解属性说明:

  • paramType:参数位置,如 pathbody 等。
  • name:参数代表的含义。
  • value:参数名称。
  • dataType:参数类型,有 stringinteger 两种。
  • required:是否必须。
  • defaultValue:参数默认值。
@ApiImplicitParams

修饰 Controller 中的方法,描述一组参数,io.swagger.annotations.ApiImplicitParam 对象集合。

@ApiResponse

响应配置。
注解属性说明:

  • code:HTTP 状态码。
  • message:描述。
  • response:默认响应类 Void
  • reference:参考 ApiOperation 中配置。
  • responseHeaders:参考 ResponseHeader 中配置。
  • responseContainer:参考 ApiOperation 中配置。
@ApiResponses

响应集配置。
注解属性说明:

  • value:多个ApiResponse配置。
@ResponseHeader

响应头设置。
注解属性说明:

  • name:响应头名称。
  • description:响应头描述。
  • response:默认响应类 Void
  • responseContainer:参考 ApiOperation 中配置。

基础示例

  1. 创建 Spring Boot 工程,参考:IntelliJ IDEA 创建 Spring Boot 工程

  2. 生成的 pom 文件如下,注意需要添加 springfox-swagger2springfox-swagger-ui 依赖。

<?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.2.5.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>tutorial.spring.boot</groupId>
    <artifactId>spring-boot-swagger2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-swagger2</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <swagger2.version>2.9.2</swagger2.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  1. 添加 Swagger2 配置类。
package tutorial.spring.boot.swagger2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * 启用 Springfox swagger 2 的配置类
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    /**
     * 注入 springfox.documentation.spring.web.plugins.Docket 对象
     */
    @Bean
    public Docket petApi() {
        // Docket 是 Springfox 主要的 API 配置机制,初始化 Swagger 2.0 规范
        return new Docket(DocumentationType.SWAGGER_2)
                /*
                 * select() 返回 springfox.documentation.spring.web.plugins.ApiSelectorBuilder 实例,
                 * 对 Swagger 暴露的端点执行细粒度控制。
                 */
                .select()
                /*
                 * apis(RequestHandlerSelectors.any()) 允许使用谓词选择 RequestHandler,
                 * 此处示例使用任意谓词(默认),
                 * 开箱即用的谓词有:any, none, withClassAnnotation, withMethodAnnotation, basePackage。
                 */
                .apis(RequestHandlerSelectors.any())
                /*
                 * paths(PathSelectors.any()) 允许使用谓词选择 Path,
                 * 此处示例使用任意谓词(默认),
                 * 开箱即用的谓词有:regex, ant, any, none
                 */
                .paths(PathSelectors.any())
                // 配制完 api 和 path 后需要构建选择器
                .build();
    }
}
  1. 定义含 Swagger2 注解的模型类。
package tutorial.spring.boot.swagger2.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDate;
import java.util.Objects;

@ApiModel(value = "用户", description = "用户类 User")
public class User {

    @ApiModelProperty(value = "唯一标识", hidden = true)
    private Long id;

    @ApiModelProperty(value = "账号", position = 1, required = true, notes = "用户登录系统的账号",
            accessMode = ApiModelProperty.AccessMode.READ_WRITE)
    private String account;

    @ApiModelProperty(value = "姓名", position = 2, allowEmptyValue = true)
    private String name;

    @ApiModelProperty(value = "出生日期", position = 3, required = true, example = "1990-01-01")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private LocalDate birth;

    public Long getId() {
        return id;
    }

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

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public LocalDate getBirth() {
        return birth;
    }

    public void setBirth(LocalDate birth) {
        this.birth = birth;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        User user = (User) o;
        return Objects.equals(id, user.id) &&
                Objects.equals(account, user.account) &&
                Objects.equals(name, user.name) &&
                Objects.equals(birth, user.birth);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, account, name, birth);
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", account='" + account + '\'' +
                ", name='" + name + '\'' +
                ", birth=" + birth +
                '}';
    }
}
  1. 定义含 Swagger2 注解的控制器类(controller)。
package tutorial.spring.boot.swagger2.controller;

import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import tutorial.spring.boot.swagger2.model.User;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "/user", description = "用户管理")
@RestController
@RequestMapping(value = "/user")
public class UserController {

    /**
     * 模拟用户信息
     */
    private static Map<Long, User> users = new HashMap<>();

    @ApiOperation(value = "查询用户", notes = "根据 ID 查询单个用户")
    @ApiImplicitParam(name = "id", value = "用户唯一标识", required = true, example = "1")
    @GetMapping("/{id}")
    public User get(@PathVariable long id) {
        return users.get(id);
    }

    @ApiOperation(value = "查询所有用户")
    @GetMapping("/")
    public Collection<User> list() {
        return users.values();
    }

    @ApiOperation(value = "根据 ID 删除用户")
    @DeleteMapping("/{id}")
    public User remove(@ApiParam(name = "id", value = "用户唯一标识", required = true, example = "1") @PathVariable long id) {
        return users.remove(id);
    }

    @ApiOperation(value = "创建用户")
    @PostMapping("/")
    public User save(@ModelAttribute User user) {
        return users.put(user.getId(), user);
    }

    @ApiOperation(value = "更新用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户唯一标识", required = true, example = "1"),
            @ApiImplicitParam(name = "user", value = "用户数据", required = true)
    })
    @PutMapping("/{id}")
    public User update(@PathVariable Long id, @RequestBody User user) {
        return users.put(id, user);
    }
}
  1. 启动应用,打开浏览器访问 http://localhost:8080/swagger-ui.html 显示所有 API 列表。

  2. 浏览器访问 http://localhost:8080/v2/api-docs 显示所有接口的 JSON 描述文件。


总结

Swagger2 有一个缺陷导致实际生产使用中利用率较低,即对代码的侵入性太高,这也导致了很多公司未使用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,198评论 4 359
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,663评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,985评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,673评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,994评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,399评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,717评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,407评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,112评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,371评论 2 241
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,891评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,255评论 2 250
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,881评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,010评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,764评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,412评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,299评论 2 260

推荐阅读更多精彩内容