Introduction of Swagger

produce

Front-end and back-end integration, the front-end or back-end cannot be “timely negotiated, resolved as soon as possible”, resulting in a cluster of problems, Swagger can track the latest API in real time, reduce the risk of inheritance

The characteristics of

  1. The most popular API framework in the world
  2. Api documents are automatically generated online => Api documents are updated with Api definitions
  3. Run directly, test the API online
  4. Support for multiple languages (e.g. Java, PHP, etc.)
  5. Liverpoolfc.tv: swagger. IO /

SpringBoot integration Swagger

  1. Create a Springboot-Web project
  2. Add the dependencies needed to integrate Swagger
<! -- SpringBoot with swagger -->
        <! -- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>
        <! -- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>

Copy the code

If the imported version is 3.0.0 or higher, you need to add the following dependency

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
Copy the code
  1. Write the configuration class for SwaggerSwaggerConfigTo configure a Swagger
@Configuration / / configuration class
@EnableSwagger2// Enable automatic configuration of Swagger2
public class SwaggerConfig {}Copy the code
    • If the import dependency is 3.0.0, directly through http://localhost:8080/swagger-ui.html
    • If it is 3.0.0, go to the main boot class to add@EnableOpenApiAnnotate and passhttp://localhost:8080/swagger-ui/index.htmlaccess

The main start class

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

@EnableOpenApi
@SpringBootApplication
public class Springboot09SwaggerApplication {

    public static void main(String[] args) { SpringApplication.run(Springboot09SwaggerApplication.class, args); }}Copy the code
  1. Results:

Configure Swagger (in SwaggerConfig)

  1. createDocketExample to configure Swagger
  2. throughapiInfo()Property Configures document information
  3. Docket instances associate apiInfo() to configure Swagger interface information.
package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

import java.util.ArrayList;


@Configuration // This is a configuration class
@EnableSwagger2 // Enable Swagger2 auto-configuration
public class SwaggerConfig {
    // Configure Swagger: The Swagger instance Bean is a Docket, so configure Swagger by configuring the Docket instance.
    @Bean
    public Docket docket(a){// Configure docket to set Swagger parameters
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());/ / associated apiInfo ()
    }

    // Configure the document information
    private ApiInfo apiInfo(a){
        Contact contact = new Contact("Author blog"."https://juejin.cn/user/703307009491261"."[email protected]");
        return new ApiInfo(
                "That's simple Swagger..."./ / title
                "This is a good thing. It works."./ / description
                "V10.0 +"./ / version
                "https://juejin.cn/user/703307009491261".// Organize links
                contact,// Contact information
                "Apach permission"./ / permission
                "https://www.apache.org/".// License link
                new ArrayList<>()/ / extension); }}Copy the code
  1. Running results:

  1. Compare the modified information in the configuration document

Configuring scan Interfaces

Configure how to scan interfaces using the select() method.

    @Bean
    public Docket docket(a){// Configure docket to set Swagger parameters
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())/ / associated apiInfo ()
                .select()// Scan interfaces using the select() method
                / / RequestHandlerSelectors basePackage according to package scanning, a common form
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .build()
                ;
    }
Copy the code

Interface scanning mode

any() // Scan all. All interfaces in the project will be scanned
none() // Do not scan interfaces
// Scan with annotations on methods, such as withMethodAnnotation(getMapping.class) only scan get requests
withMethodAnnotation(final Class<? extends Annotation> annotation)
WithClassAnnotation (Controller.class) scans only interfaces in classes that have Controller annotations
withClassAnnotation(final Class<? extends Annotation> annotation)
basePackage(final String basePackage) // Scan interfaces based on packet paths
Copy the code

In addition to this, we can configure interface scan filtering through Paths ()

    @Bean
    public Docket docket(a){// Configure docket to set Swagger parameters
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())/ / associated apiInfo ()
                .select()// Scan interfaces using the select() method
                / / RequestHandlerSelectors basePackage according to package scanning, a common form
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                // How does the configuration filter through path, i.e. here (scanning and filtering) interfaces starting with /example
                .paths(PathSelectors.ant("/example/**"))
                .build()
                ;
    }
Copy the code

Filtering method

Switch to configure Swagger

Configure Swagger by using the enable() method. The default is true

 @Bean
    public Docket docket(a){// Configure docket to set Swagger parameters
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())/ / associated apiInfo ()
                .enable(false) // Configures whether Swagger is enabled. If false, it will not be accessible in the browser
                .select()// Scan interfaces using the select() method
                / / RequestHandlerSelectors basePackage according to package scanning, a common form
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                // How do you configure filtering through path, where only interfaces whose requests start with /example are scanned
                .paths(PathSelectors.ant("example/**"))
                .build()
                ;
    }
Copy the code

Results:

  • Can be used to dynamically set the project environment at the same time Swagger different switch situation

Configuring API Grouping

There is no configuration group by default, only one default

We can configure groups by groupName()

 @Bean
    public Docket docket(a){// Configure docket to set Swagger parameters
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())/ / associated apiInfo ()
                .groupName("group")
                .enable(true) // Configures whether Swagger is enabled. If false, it will not be accessible in the browser
                .select()// Scan interfaces using the select() method
                / / RequestHandlerSelectors basePackage according to package scanning, a common form
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                // How do you configure filtering through path, where only interfaces whose requests start with /example are scanned
                .paths(PathSelectors.ant("example/**"))
                .build()
                ;
    }
Copy the code

Results:

  • We can also create more than onedocketTo configure multiple groups
@Bean
public Docket docket1(a){
   return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
public Docket docket2(a){
   return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
public Docket docket3(a){
   return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
}
Copy the code

Configuring entity Classes

  1. Creating an entity Class
  2. Add annotation information to the entity class
package com.example.pojo;

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

@apiModel (" user entity ")
public class User {
    @ ApiModelProperty (" user id ")
    public int id;// It must be a public property, private property cannot be scanned
    @apiModelProperty (" user name ")
    public String name;
}

Copy the code
  1. Write the return view in the Controller layer
  • As long as this entity is on the return value of the request interface (even if it is generic), it can be mapped to the entity item:
package com.example.controlller;

import com.example.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
 @PostMapping(value = "/user")
    public User getUser(a){
        return newUser(); }}Copy the code

Among them

  • @apiModel adds comments to the class
  • @apiModelProperty adds comments to class attributes
  1. Results: