Swagger

Swagger Swagger

1.1 Learning Objectives:

  • 1. Understand the role and concept of Swagger
  • 2. Understand front and rear end separations
  • 3. Incorporate Swagger into SpringBoot

1.2 Understanding the anterior and posterior separation:

Vue + SpringBoot

Backend era:

The front end only manages static pages;

HTML ==> Back end, template engine

JSP==> The back end is the workhorse


The era of anterior and posterior separation:

  • Back-end: Back-end control layer, service layer, data access layer [back-end team]

  • Front end: front control layer [front end team]

    • Counterfeit back-end data, JSON.
    • Front-end engineering can be started without the back end
  • How do the front and back ends interact? = = > API

  • The front and back ends are relatively independent, loosely coupled!

  • The front and back ends can even be deployed on different servers!

This raises a question:

  • Before and after the end of the integration and coordination, front-end and back-end personnel can not do “even if the negotiation, as soon as possible”, eventually lead to a centralized outbreak of problems!

Solution:

  • First, specify the Schema[outline of the plan] to update the latest API in real time, reducing the risk of integration.
  • Early years: Specify a Word project document.
  • Front and rear end separation:
    • Front-end test Back-end interface: Postman
    • The back-end provides an interface that needs to be updated in real time with the latest news and changes!

1.3 introduction:

  • Claims to be the most popular Api framework in the world
  • RestFul Api document automatic online generation tool => Api documents are updated at the same time as Api definitions
  • Run directly, you can test the API interface online
  • Support for multiple languages

Liverpoolfc.tv: swagger. IO /

1.4 Used in projects

Using Swagger in a project requires Springbox

  • Swagger2
  • UI

2. Springboot integrates Swagger

Use the Swagger

Configuration requirements: JDK 1.8 + Otherwise Swagger2 will not run

Steps:

2.1 Create a SpringBoot-Web project

2.2 Adding Maven dependencies

  • The 3.0.0 version cannot open the Swagger web page
<! -- 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>
Copy the code

2.3 Writing HelloController,

Write HelloController and test to make sure it runs successfully!

@RestController
public class HelloController {

    @RequestMapping(value = "/hello")
    public String hello(a){
        return "hello"; }}Copy the code

2.4 use Swagger

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

@Configuration / / configuration class
@EnableSwagger2// Turn on autoconfiguration for Swagger2
public class SwaggerConfig {}Copy the code

2.5 Access test:

Access test:http://localhost:8080/swagger-ui.html, you can see the Swagger interface;


Three, configuration Swagger

3.1 configuration Docket

Swagger instance beans are Docket, so configure Swaggger by configuring the Docket instance.

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

3.2 You can use the apiInfo() attribute to configure the document information

    // Configure Swagger information =apiInfo
    private ApiInfo apiInfo(a){
        // Author information
        Contact contact = new Contact("Light as a breeze."."https://blog.csdn.net/QQ1043051018"."[email protected]");
        return new ApiInfo(
                "Cool SwaggerApi Documentation"."Do your best, and God will do the rest!"."v1.0"."https://blog.csdn.net/QQ1043051018",
                contact,
                "Apache 2.0"."http://www.apache.org/licenses/LICENSE-2.0".newArrayList()); }}Copy the code
// Configure the document information
private ApiInfo apiInfo(a) {
   Contact contact = new Contact("Contact name"."http://xxx.xxx.com/ Contact Access Links"."Contact Email");
   return new ApiInfo(
           "Swagger learning"./ / title
           "Learn to demonstrate how to configure Swagger"./ / description
           "v1.0"./ / version
           "Http://terms.service.url/ organization links".// Organize links
           contact, // Contact information
           "Apach 2.0 License"./ / permission
           "License Link".// License the connection
           new ArrayList<>()/ / extension
  );
}
Copy the code

3.3 Associating a Docket instance with apiInfo()

    // Docket instance with Swagger configured
    @Bean
    public Docket docket(a) {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }
Copy the code

3.4 Restarting a Project

Access to the testhttp://localhost:8080/swagger-ui.htmlLet’s see what happens;

Configure the scan interface

4.1 Scanning interfaces

When building Docket, configure how to scan the interface using the select() method.

    // Docket instance with Swagger configured
    @Bean
    public Docket docket(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                RequestHandlerSelectors configure how to scan interfaces using.select()
                .select()
                / / RequestHandlerSelectors, configuration to scan the way of the interface
                //basePackage: specifies the specific package to scan
                .apis(RequestHandlerSelectors.basePackage("com.cy.swagger.controller"))
                .build();
    }
Copy the code

4.2 Restarting a Project Test

Since we are configured to scan the interface based on the package path, we can only see one class

4.3 Comments on all configuration methods

In addition to configuring the packet path to scan an interface, you can also configure other methods to scan an interface. Here are all the configuration methods:

any() // Scan all, all interfaces in the project will be scanned
none() // Do not scan the interface
// scan only get requests using method annotations, such as withMethodAnnotation(getmapping.class)
withMethodAnnotation(final Class<? extends Annotation> annotation)
// Scan only the interface in the class that has the Controller annotation by using an annotation on the class, such as.withClassAnnotation(controller.class)
withClassAnnotation(final Class<? extends Annotation> annotation)
basePackage(final String basePackage) // Scan the interface according to the packet path
Copy the code

4.4 Configuring Interface scan Filtering

In addition, we can also configure interface scan filtering:

       // How to configure filtering through path, that is, scan only the interface whose request starts with /cy
      .paths(PathSelectors.ant("/cy/**"))
Copy the code
@Bean
public Docket docket(a) {
   return new Docket(DocumentationType.SWAGGER_2)
      .apiInfo(apiInfo())
      .select()RequestHandlerSelectors configure how to scan interfaces using.select()
      .apis(RequestHandlerSelectors.basePackage("com.cy.swagger.controller"))
       // How to configure filtering through path, that is, scan only the interface whose request starts with /cy
      .paths(PathSelectors.ant("/cy/**"))
      .build();
}
Copy the code

4.5 optional value

The alternative values here are

any() // Any request will be scanned
none() // No requests will be scanned
regex(final String pathRegex) // Control by regular expression
ant(final String antPattern) // Control via ant()
Copy the code

Swagger switch configuration

5.1 Configuring whether to enable Swagger,

Use the enable() method to configure whether swagger is enabled. If false, swagger will no longer be accessible in the browser

// Configure whether Swagger is enabled. If false, it will not be accessible in the browser
.enable(false)
Copy the code
    // Docket instance with Swagger configured
    @Bean
    public Docket docket(a) {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // Configure whether Swagger is enabled. If false, it will not be accessible in the browser
                .enable(false)
                RequestHandlerSelectors configure how to scan interfaces using.select()
                .select()
                / / RequestHandlerSelectors, configuration to scan the way of the interface
                //basePackage: specifies the specific package to scan
                .apis(RequestHandlerSelectors.basePackage("com.cy.swagger.controller"))
                .build();
    }
Copy the code

5.2 How to Think about Dynamic Configuration?

How to dynamically configure swagger to show when the project is in test, Dev environment, but not when the project is in PROd?

  • Check whether the current environment flag=false
  • Inject the enable (flag)

Create application-dev.properties and application-prod.properties respectively

  • They represent the development phase and the launch phase

application.properties

spring.profiles.active=dev
Copy the code

application-dev.properties

server.port=8081
Copy the code

application-prod.properties

server.port=8081
Copy the code

Think: How do I implement this in my code?

    @Bean
    public Docket docket(Environment environment) {
        // Set the environment to display swagger
        Profiles profiles = Profiles.of("dev"."test");
        // Determine whether the current environment is in the environment
        // Accept this parameter by enable() to determine whether to display it
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // Configure whether Swagger is enabled. If false, it will not be accessible in the browser
                .enable(flag)
                RequestHandlerSelectors configure how to scan interfaces using.select()
                .select()
                / / RequestHandlerSelectors, configuration to scan the way of the interface
                //basePackage: specifies the specific package to scan
                .apis(RequestHandlerSelectors.basePackage("com.cy.swagger.controller"))
                .build();
    }
Copy the code

5.3 Dev Configuration file

You can add a dev configuration file to the project to see the effect!

  • http://localhost:8081/swagger-ui.html#/basic-error-controller

Configure API groups

6.1 Configuring Groups

If no group is configured, the default value is default. You can configure groups using the groupName() method:

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

6.2 Restarting a Project To view groups

6.3 How Do I Configure Multiple Groups?

To configure multiple groups, you only need to configure multiple Dockets:

    @Bean
    public Docket docket1(a){
        return new Docket(DocumentationType.SWAGGER_2).groupName("Xiao li");
    }
    @Bean
    public Docket docket2(a){
        return new Docket(DocumentationType.SWAGGER_2).groupName("Little red");
    }
    @Bean
    public Docket docket3(a){
        return new Docket(DocumentationType.SWAGGER_2).groupName("Xiao Ming");
    }
Copy the code

6.4 Restart the project

7. Entity configuration

7.1 Creating an entity Class

  • @apiModel Annotates the class
  • ApiModelProperty annotates class attributes
@ApiModel(" User Entity ")
public class User {
   @ApiModelProperty(" username ")
   public String username;
   @ ApiModelProperty (" password ")
   public String password;
}
Copy the code

7.2 Return value of the request interface

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

    // As long as there is an entity class in the return value of our interface, it will be scanned into The Swagger
    @RequestMapping("/getUser")
    public User getUser(a){
        return new User();
    }
Copy the code

7.3 Restarting a Test

Note: It’s not because the @ApiModel annotation makes the entities appear here, but any entities that appear on the return value of the interface method will appear here, and the @ApiModel and @ApiModelProperty annotations just annotate the entities.

Commonly used annotations

All annotations for Swagger are defined under the io.swagger. Annotations package

Here are some of the most frequently used ones, and those not listed can be referred to separately:

Swagger annotations Simple instructions
@api (tags = “XXX module description “) Applies to module classes
@apiOperation (” XXX Interface description “) Applies to interface methods
XxxPOJO @ ApiModel (” “) Applies to model classes: VO, BO
@apiModelProperty (value = “XXX “,hidden = true) On class methods and properties. Set hidden to true to hide the property
@apiparam (” XXX parameter description “) Applies to parameters, methods, and fields, similar to @ApiModelProperty

We can also configure some comments for the requested interface

@ApiOperation(" Wind interface ")
@PostMapping("/cy")
@ResponseBody
public String qingfeng(ApiParam(" This name will be returned ")String username){
   return username;
}
Copy the code

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!

Conclusion:

1. We can add comments to properties or interfaces that are difficult to understand with Swagger 2. Interface documents are updated in real time. 3. You can test online

[Note] For the official release, close the Swagger! For security reasons and to save running memory.

Swagger is foolproof compared to traditional Postman or Curl testing interfaces, requires no documentation (well written is documentation) and is less error-prone, just entry data and click Execute, and with an automation framework, virtually no human intervention is required.

Swagger is an excellent tool that has been used by many small and medium-sized Internet companies across the country. It is also more suitable for rapid iterative development than the traditional way of publishing a Word interface document and then testing it. Of course, a reminder to turn off Swagger in formal environments, both for security reasons and to save runtime memory.

Extension: Other skin

We can import the different package to achieve different skin definition: 1, the default of http://localhost:8080/swagger-ui.html

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

2, the bootstrap visit http://localhost:8080/doc.html – UI blue

<! Swagger-bootstrap-ui package /doc.html-->
<dependency>
   <groupId>com.github.xiaoymin</groupId>
   <artifactId>swagger-bootstrap-ui</artifactId>
   <version>1.9.1</version>
</dependency>
Copy the code

3, Layui visit http://localhost:8080/docs.html – UI black

<! -- Introduce swagger- uI-layer package /docs.html-->
<dependency>
   <groupId>com.github.caspar-chen</groupId>
   <artifactId>swagger-ui-layer</artifactId>
   <version>1.1.3</version>
</dependency>
Copy the code

4, mg – visit http://localhost:8080/document.html UI white

<! Swagger-ui-layer package /document.html-->
<dependency>
   <groupId>com.zyplayer</groupId>
   <artifactId>swagger-mg-ui</artifactId>
   <version>1.0.6</version>
</dependency>
Copy the code