SpringBoot: Integrating Swagger

Excerpted from the SpringBoot notes in Java at station B Kuangshenshuo, the SpringBoot transmission gate
UP master is very nice, the courses are vivid and vivid, welcome to support.

Introduction

I believe that both front-end and back-end development have been more or less tortured by interface documents. The front end often complains that the interface documents given by the back end are inconsistent with the actual situation. The backend feels that writing and maintaining interface documents will consume a lot of energy, and it is often too late to update. In fact, no matter whether the front end calls the back end or the back end calls the back end, we all expect a good interface document. But this interface document is just like comments to programmers. They often complain that the code written by others does not write comments, but when writing code by themselves, the most annoying thing is to write comments. Therefore, it is not enough to standardize everyone only through coercion. As time goes by and the version is iterated, the interface documentation often cannot keep up with the code.

solution

First define the schema [the outline of the plan], and track the latest API in real time to reduce integration risks

Swagger

  • Known as the world's most popular API framework
  • Restful Api document online automatic generator => API document and API definition are updated synchronously
  • Run directly, test API online
  • Support multiple languages ​​(such as: Java, PHP, etc.)
  • Official website: https://swagger.io/

SpringBoot integrates Swagger

Add Mavex dependency

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

Configure Swagger

1. The Swagger instance bean is Docket, so configure Swagger by configuring the Docket instance.

@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配 置
public class SwaggerConfig {
    
    
    //配置了swagger的Docket的bean实例
  @Bean //配置docket以配置Swagger具体参数
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2);
   }
}

2. Document information can be configured through the apiInfo() attribute

    //配置文档信息
    private ApiInfo apiInfo() {
    
    
        //人员信息
        Contact contact = new Contact("联系人名字", "http://xxx.xxx.com/联系人访问链接", "联系人邮箱");
        return new ApiInfo(
                "Swagger学习", // 标题
                "学习演示如何配置Swagger", // 描述
                "v1.0", // 版本
                "http://terms.service.url/组织链接", // 组织链接
                contact, // 联系人信息
                "Apach 2.0 许可", // 许可
                "许可链接", // 许可连接
                new ArrayList<>()// 扩展
        );
    }

Configure scan interface

1. When building a Docket, configure how to scan the interface through the select() method.

    @Bean
    public Docket docket(Environment environment) {
    
    
        // 设置要显示swagger的环境
        Profiles of = Profiles.of("dev", "test");
        // 判断当前是否处于该环境
        // 通过 enable() 接收此参数判断是否要显示
        boolean b = environment.acceptsProfiles(of);
        System.out.println(b);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("凯")
                .enable(b) //配置是否启用Swagger,如果是false,在浏览器将无法访问
                .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
                .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
                //withMethodAnnotation扫描方法上的注解
                //.apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
                // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
                // .paths(PathSelectors.ant("/kuang/**"))
                .build();
    }

2. Restart the project test. Since we configure the scanning interface according to the path of the package, we can only see one class.
3. In addition to configuring the scanning interface through the package path, you can also configure other ways to scan the interface. Here, comment on all the configurations Way:

any() // Scan all, all interfaces in the project will be scanned to
none() // Do not scan interfaces
// Scan through annotations on methods, such as withMethodAnnotation(GetMapping.class) only scan get requests
withMethodAnnotation(final Class< ? extends Annotation> annotation)
// scan through annotations on the class, such as .withClassAnnotation(Controller.class) only scans interfaces in classes with controller annotations
withClassAnnotation(final Class<? extends Annotation> annotation)
basePackage(final String basePackage) // Scan the interface according to the package path

4. In addition, we can also configure interface scanning filtering

@Bean
public Docket docket() {
    
    
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}

5. Configure whether to enable swagger through the enable() method. If it is false, swagger will not be accessible in the browser

@Bean
public Docket docket(Environment environment) {
    
    
   // 设置要显示swagger的环境
   Profiles of = Profiles.of("dev", "test");
   // 判断当前是否处于该环境
   // 通过 enable() 接收此参数判断是否要显示
   boolean b = environment.acceptsProfiles(of);
   
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(b) //配置是否启用Swagger,如果是false,在浏览器将无法访问
      .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口
      .apis(RequestHandlerSelectors.basePackage("com.kuang.swagger.controller"))
       // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口
      .paths(PathSelectors.ant("/kuang/**"))
      .build();
}

Configure API grouping
insert image description here

   @Bean
    public Docket docket1() {
    
    
        return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
    }

    @Bean
    public Docket docket2() {
    
    
        return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
    }

    @Bean
    public Docket docket3() {
    
    
        return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
    }

Entity class configuration

1. Create a new entity class

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel("用户实体")
public class User {
    
    
    @ApiModelProperty("用户名")
    public String username;
    @ApiModelProperty("密码")
    public String password;
}

insert image description here

Common Notes

Swagger annotations brief description
@Api(tags = "xxx module description") acting on the module class
@ApiOperation("xxx interface description") acting on the interface method
@ApiModel("xxxPOJO Description") Act on the model class: such as VO, BO
@ApiModelProperty(value = "xxx attribute description", hidden = true) Acts on class methods and properties, setting hidden to true can hide the property
@ApiParam("xxx parameter description") Acts on parameters, methods and fields, similar to @ApiModelProperty

Guess you like

Origin blog.csdn.net/qq_43161404/article/details/122311792