Swagger

前言

  • Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

  • 总体目标是使客户端和文件系统作为服务器以同样的速度来更新。

  • 文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。

  • Swagger 让部署管理和使用功能强大的 API 从未如此简单。

  • Swagger 官网

  • Swagger UI

  • Swagger-bootstrap-ui 开发指南

  • SpringBoot 整合 Swagger

1、Swagger

  • Swagger 注解
关键字 介绍 示例代码
@Api 使用在类上,表明是 swagger 资源。
生成的 api 文档会根据 tags 分类,就是这个 controller 中的所有接口生成的接口文档都会在 tags 这个 list 下。tags 如果有多个值,会生成多个 list,每个 list 都显示所有接口。
value 的作用类似 tags,但是不能有多个值。
@Api(value="ContactController", tags={"Contact Api"})
public class ContactController { }
@ApiOperation 使用于在方法上,表示一个 http 请求的操作。value 用于方法描述,notes 用于提示内容,tags 可以重新分组(视情况而用) @ApiOperation(value = "Retrieve Tenant List")
public Response<PageResponse<Tenant>> listTenant( ) { }
@ApiModel 使用在类上,表示对类进行说明,用于参数用实体类接收。value 表示对象名,description 描述
@ApiModelProperty 使用在方法,字段上,表示对 model 属性的说明或者数据操作更改。value 字段说明,name 重写属性名字,dataType 重写属性类型,required 是否必填,example 举例说明,hidden 隐藏
@ApiParam 使用在方法上或者参数上,字段说明;表示对参数的添加元数据(说明或是否必填等)。name 参数名,value 参数说明,required 是否必填

2、Swagger 配置

2.1 Spring Boot 集成

  • 导入相关依赖

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <dependencies>

    <!-- Swagger2 -->
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    </dependency>

    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
    </dependency>

    <!-- 新版(3.0)的直接加入启动器 -->
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
    </dependency>

    </dependencies>
  • 配置 Swagger

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    // SwaggerConfiguration.java

    package com.qianchia.config;

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

    @EnableSwagger2
    @Configuration
    public class SwaggerConfiguration {

    @Bean
    public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
    .apiInfo(apiInfo())
    .useDefaultResponseMessages(false)
    .enable(true)
    .select()
    .apis(RequestHandlerSelectors.basePackage("com.qianchia.controller"))
    .build();
    }

    private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
    .title("Tane")
    .version("1.0")
    .build();
    }
    }
    • 3.0 版本后不需要在加入 @enableopenapi,和 @enableswagger2 这两个注解。

    • eanble 决定了是否启动 swagger。处于安全考虑,我们在发布的时候需要关闭 Swagger。

    • basePackage 里指定扫描接口所在的路径。
    • apiInfo() 里设置 Api 描述信息。
  • 添加资源映射

    • 如果处理全局 404 时设置了 spring.mvc.throw-exception-if-no-handler-found=true和spring.resources.add-mappings=false,导致 Swagger 的资源映射有问题,所以解决办法就是手动添加资源映射。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      // SwaggerResourceConfiguration.java

      package com.tenafy.config;

      import org.springframework.context.annotation.Configuration;
      import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
      import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

      @Configuration
      public class SwaggerResourceConfiguration extends WebMvcConfigurerAdapter {

      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
      registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
      registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
      registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/statics/swagger/");
      }
      }
  • 设置免验证访问

    • 如果设置了需要用户登录才能访问 Api,需要设置免验证访问 Swagger。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      // SecurityConfiguration.java

      @EnableWebSecurity
      @Configuration
      @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
      public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

      @Override
      public void configure(WebSecurity web) throws Exception {
      // allow Swagger URL to be accessed without authentication
      web.ignoring().antMatchers(
      "/api/auth/**",
      "/error**",
      "/webjars/**",
      "/v2/api-docs", // swagger api json
      "/swagger-ui.html", // swagger ui
      "/swagger-resources", // 用来获取 api-docs 的 URI
      "/swagger-resources/**",
      "/swagger-resources/configuration/ui", // 用来获取支持的动作
      "/swagger-resources/configuration/security" // 安全选项
      );
      }
      }
  • 使用 Swagger

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    // ContactController.java

    @RestController
    @Api(value="ContactController", tags={"Contact Api"}) // 使用在类上,表明是 swagger 资源。
    @RequestMapping("/api")
    public class ContactController {

    @Autowired
    private ContactService contactService;

    @Autowired
    private AuthService authService;

    @ApiOperation(value = "Retrieve Tenant List") // 使用于在方法上,表示一个 http 请求的操作。
    @PostMapping("/tenants")
    public Response<PageResponse<Tenant>> listTenant(@ModelAttribute PageRequest pageRequest,
    @RequestBody(required = false) TenantQueryRequest request) throws AccessDeniedException {
    return new Response<PageResponse<Tenant>>().withData(contactService.listTenant(authService.currentOrgId(), request, pageRequest));
    }

    @ApiOperation(value = "Create New Tenant") // 使用于在方法上,表示一个 http 请求的操作。
    @PostMapping("/tenant")
    public Response addTenant(@Validated @RequestBody NewTenantRequest request) throws AccessDeniedException {
    try {
    contactService.createTenant(authService.currentOrgId(), request);
    return new Response();
    } catch (DuplicatedUserException e) {
    return new Response(9001,e.getMessage());
    }
    }
    }
文章目录
  1. 1. 前言
  2. 2. 1、Swagger
  3. 3. 2、Swagger 配置
    1. 3.1. 2.1 Spring Boot 集成
隐藏目录