天天看点

SpringBoot集成Swgger2

Swagger 简介

​​Swagger​​ 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。(Swagger的作用是定义了一个文档的规范。)

开源的部分包括:

  • OpenAPI Specification:API规范,规定了如何描述一个系统的API。
  • Swagger Codegen:用于通过API规范生成服务端和客户端代码。
  • Swagger Editor:用来编写API规范。
  • Swagger UI:用于展示API规范。

非开源的部分包括:

  • Swagger Hub:云服务,相当于Editor + Codegen + UI。
  • Swagger Inspector:手动测试API的工具。
  • SoapUI Pro:功能测试和安全测试的自动化工具。
  • LoadUI Pro:压力测试和性能测试的自动化工具。

SpringFox

​​SpringFox​​ 是一个开源的API Doc的框架,可以将我们的Controller中的方法以文档的形式展现。

SpringFox 优势是:

  1. 根据代码自动生成API文档,减轻文档维护工作量。
  2. 通过生成文档的web页面可以,我们可以直接发起请求,对接口进行测试。

SpringFox 页面布局

整体布局

SpringBoot集成Swgger2

接口请求布局

SpringBoot集成Swgger2

接口响应布局

SpringBoot集成Swgger2

集成Swagger

引入jar包

<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>      

如果是Spring5可以直接使用3.0:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>      

配置Swagger界面

更多配置可以参考​​SpringFox​​。Swagger实例Bean是Docket,所以必须通过配置Docket实例来配置Swaggger,如果需要配置不同的组,那么只需要实例化多个Docket就行。

package com.xiaolyuh.config;

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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    //api接口包扫描路径
    public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.xiaolyuh.controller";
    private static final String VERSION = "1.0.0";

    @Value("${swagger.enable:false}")
    private boolean swaggerEnable;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 分组信息
                .groupName("默认分组")
                .enable(swaggerEnable)
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                // 可以根据url路径设置哪些请求加入文档,这里可以配置不需要显示的文档
                .paths(PathSelectors.any())
                //paths: 这里是控制哪些路径的api会被显示出来,比如下方的参数就是除了/user以外的其它路径都会生成api文档
                // .paths((String a) ->
                //       !a.equals("/user"))
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //设置文档的标题
                .title("用户信息文档")
                // 设置文档的描述
                .description("文档描述信息或者特殊说明信息")
                // 设置文档的版本信息-> 1.0.0 Version information
                .version(VERSION)
                // 设置文档的License信息->1.3 License information
                .termsOfServiceUrl("http://www.baidu.com")
                // 设置联系人
                .contact(new Contact("汪雨浩", "http://www.baidu.com", "[email protected]"))
                .build();
    }
}      

接口定义

Controller

@Api(tags = "用户信息查询", hidden = false)
@RestController
public class PersonController {

    @PostMapping("save")
    @ApiOperation(value = "保存用户信息", httpMethod = "POST")
    public Result<PersonResponse> save(@RequestBody PersonRequest person) {
        person.setId(12L);
        PersonResponse personResponse = new PersonResponse();
        BeanUtils.copyProperties(person, personResponse);
        return Result.success(personResponse);
    }

    @PostMapping("update")
    @ApiOperation(value = "更新用户信息", httpMethod = "POST")
    public Result<PersonResponse> update(@RequestBody PersonRequest person) {
        person.setId(12L);
        PersonResponse personResponse = new PersonResponse();
        BeanUtils.copyProperties(person, personResponse);
        return Result.success(personResponse);
    }
}      

VO

@Data
@ApiModel("保存用户信息接口请求参数")
public class PersonRequest {
    @ApiModelProperty(value = "ID",example = "13",  hidden = true)
    private Long id;

    @ApiModelProperty(value = "用户名", example = "用户名", allowEmptyValue = true, required = true)
    private String name;

    @ApiModelProperty(value = "年龄", example = "29", allowEmptyValue = false, required = true)
    private Integer age;

    @ApiModelProperty(value = "地址", example = "地球村", allowEmptyValue = false, required = true)
    private String address;
}      

查看文档

启动项目打开​​http://localhost:8080/swagger-ui.html#​​。

SpringBoot集成Swgger2

Swgger常用注解

注解 说明
@Api(tags = “用户信息查询”, hidden = false) 作用在Controller上,表示是有个模块
@ApiOperation(value = “保存用户信息”, httpMethod = “POST”) 作用在Controller的方法上,表示一个接口
@ApiModel(“保存用户信息接口请求参数”) 作用在request、response、VO、BO等实体类上,表示定一个模型
@ApiModelProperty(value = “用户名”, example = “用户名”, allowEmptyValue = true, required = true) 作用在VO、BO的属性上,表示一个属性说明。

源码地址