[3] Swagger - solve the problem of front and rear end fighting

Spring Boot integrated swagger

Article reprint address Supporting video address

Using Swagger

Requirement: jdk 1.8+ (otherwise swagger2 cannot run)

Steps:

1. Create a springboot web project

2. Add Maven dependency

<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. Write HelloController and test to ensure successful operation!

4. To use Swagger, we need to write a configuration class -SwaggerConfig to configure Swagger

@Configuration //Configuration class
@EnableSwagger2// Turn on automatic configuration of Swagger2
public class SwaggerConfig {  
}

5. Access test: http://localhost:8080/swagger -Ui HTML, you can see the interface of swagger;

Configure Swagger

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

@Bean //Configure docket to configure Swagger specific parameters
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2);
}

2. You can configure the document information through the apiInfo() attribute

//Configure document information
private ApiInfo apiInfo() {
   Contact contact = new Contact("Contact name", "http://Xxx Xxx Com/ contact access link "," contact email ");
   return new ApiInfo(
           "Swagger learning", // title
           "Learn to demonstrate how to configure Swagger", // describe
           "v1.0", // version
           "http://Terms Service Url/ organization link ", / / organization link
           contact, // contact information 
           "Apach 2.0 permit", // permit
           "License link", // License connection
           new ArrayList<>()// extend
  );
}

3. apiInfo() on Docket instance Association

@Bean
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}

4. Restart the project and access the test http://localhost:8080/swagger -Ui HTML to see the effect;

Configure scan interface

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

@Bean
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()// Adopted select() method to configure the scanning interface, and RequestHandlerSelectors to configure how to scan the interface
      .apis(RequestHandlerSelectors.basePackage("com.kulipa.swagger.controller"))
      .build();
}

2. Restart the project test. Since we configured to scan the 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 methods to scan the interface. Here are all the configuration methods:

any() // Scan all. All interfaces in the project will be scanned to
none() // Do not scan interfaces
// Scan the annotation on the method. For example, withMethodAnnotation(GetMapping.class) only scans get requests
withMethodAnnotation(final Class<? extends Annotation> annotation)
// Scan through the 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 interface according to packet path

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

@Bean
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()// Adopted select() method to configure the scanning interface, and RequestHandlerSelectors to configure how to scan the interface
      .apis(RequestHandlerSelectors.basePackage("com.kulipa.swagger.controller"))
       // Configure how to filter through the path, that is, only the interfaces whose requests begin with /kulipa are scanned here
      .paths(PathSelectors.ant("/kulipa/**"))
      .build();
}

5. The optional values here are

any() // Scan for any request
none() // Do not scan for any requests
regex(final String pathRegex) // Regular expression control
ant(final String antPattern) // Control via ant()

Configuring the Swagger switch

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

@Bean
public Docket docket() {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(false) //Configure whether Swagger is enabled. If false, it will not be accessible in the browser
      .select()// Adopted select() method to configure the scanning interface, and RequestHandlerSelectors to configure how to scan the interface
      .apis(RequestHandlerSelectors.basePackage("com.kulipa.swagger.controller"))
       // Configure how to filter through the path, that is, only the interfaces whose requests begin with /kulipa are scanned here
      .paths(PathSelectors.ant("/kulipa/**"))
      .build();
}

2. How to dynamically configure the swagger to be displayed when the project is in the test and dev environments and not to be displayed when the project is in the prod environment?

@Bean
public Docket docket(Environment environment) {
   // Set up the environment to display swagger
   Profiles of = Profiles.of("dev", "test");
   // Judge whether you are currently in this environment
   // Receive this parameter through enable() to determine whether to display
   boolean b = environment.acceptsProfiles(of);
   
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .enable(b) //Configure whether Swagger is enabled. If false, it will not be accessible in the browser
      .select()// Adopted select() method to configure the scanning interface, and RequestHandlerSelectors to configure how to scan the interface
      .apis(RequestHandlerSelectors.basePackage("com.kulipa.swagger.controller"))
       // Configure how to filter through the path, that is, only the interfaces whose requests begin with /kulipa are scanned here
      .paths(PathSelectors.ant("/kulipa/**"))
      .build();
}

3. You can add a dev configuration file to the project to view the effect!

Configure API grouping


1. If grouping is not configured, the default is default. Grouping can be configured through the groupName() method:

@Bean
public Docket docket(Environment environment) {
   return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
      .groupName("hello") // Configure grouping
       // Omit configuration
}

2. Restart item view group
3. How to configure multiple groups? To configure multiple groups, you only need to configure multiple docket s:

@Bean
public Docket docket1(){
   return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
   return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docket3(){
   return new Docket(DocumentationType.SWAGGER_2).groupName("C");
}

4. Restart the project to view

Entity configuration

1. Create a new entity class

@ApiModel("User entity")
public class User {
   @ApiModelProperty("user name")
   public String username;
   @ApiModelProperty("password")
   public String password;
}

2. As long as this entity is on the return value of the request interface (even the generic type), it can be mapped to the entity item:

@RequestMapping("/getUser")
public User getUser(){
   return new User();
}

3. Restart view test
Note: it is not because the @ApiModel annotation makes the entities displayed here, but because the entities that appear on the return value of the interface method will be displayed here, and the @ApiModel and @ApiModelProperty annotations only add annotations to the entities.
@ApiModel annotates a class
@ApiModelProperty adds comments for class properties

Common notes

All the annotations of swagger are defined in io Swagger Annotations package
The following are some frequently used ones, which are not listed. Please refer to the instructions separately:

Swagger annotation Brief description
@Api(tags = "xxx module description") Act on module classes
@ApiOperation("xxx interface description") Act on interface methods
@ApiModel("xxxPOJO description") Acting on model classes: such as VO and BO
@ApiModelProperty(value = "xxx property description", hidden = true) Used on class methods and attributes. Setting hidden to true can hide the attribute
@ApiParam("xxx parameter description") It acts on parameters, methods and fields, similar to @ApiModelProperty

We can also configure some comments for the requested interface

@ApiOperation("Kulipa Interface of")
@PostMapping("/Kulipa")
@ResponseBody
public String Kulipa(@ApiParam("This name will be returned")String username){
   return username;
}

In this way, you can add some configuration information to some properties or interfaces that are difficult to understand, making it easier for people to read!

Compared with the traditional Postman or Curl method for testing interfaces, using swagger is a fool's operation. It does not require additional documentation (well written is a document) and is less prone to errors. It only needs to enter data and click Execute. If it is combined with the automation framework, it can be said that there is basically no need for manual operation.

Swagger is an excellent tool, which has been used by many small and medium-sized Internet companies in China. Compared with the traditional method of first exporting Word interface documents and then testing, it is obviously more in line with the current rapid iterative development market. Of course, I would like to remind you that you should remember to turn off swagger in the formal environment. Firstly, for security reasons, and secondly, you can save runtime memory.

Development: other skin

We can import different packages to implement different skin definitions:
1. Default access http://localhost:8080/swagger -Ui HTML

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


2. Bootstrap UI access http://localhost:8080/doc.html

<!-- lead into swagger-bootstrap-ui package /doc.html-->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.9.1</version>
</dependency>


3. Layui UI access http://localhost:8080/docs.html

<!-- lead into swagger-ui-layer package /docs.html-->
<dependency>
   <groupId>com.github.caspar-chen</groupId>
   <artifactId>swagger-ui-layer</artifactId>
   <version>1.1.3</version>
</dependency>


4. Mg UI access http://localhost:8080/document.html

<!-- lead into swagger-ui-layer package /document.html-->
<dependency>
   <groupId>com.zyplayer</groupId>
   <artifactId>swagger-mg-ui</artifactId>
   <version>1.0.6</version>
</dependency>

Tags: Java swagger

Posted by jawinn on Thu, 02 Jun 2022 03:29:50 +0530