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 依赖。



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE
        
    
    tutorial.spring.boot
    spring-boot-swagger2
    0.0.1-SNAPSHOT
    spring-boot-swagger2
    Demo project for Spring Boot

    
        1.8
        2.9.2
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            io.springfox
            springfox-swagger2
            ${swagger2.version}
        
        
            io.springfox
            springfox-swagger-ui
            ${swagger2.version}
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


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

你可能感兴趣的:(Spring Boot 集成 Swagger 2.0 生成 API 文档)