1. Swagger

Swagger is a RESTFUL interface for online document auto-generation + feature testing feature software

Swagger Swagger is a specification and complete framework for generating, describing, invoking, and visualizing RESTful Web services. The overall goal is to have the client and the file system update at the same rate as the server. The file’s methods, parameters, and models are tightly integrated into the server-side code, allowing the API to always be synchronized. Swagger makes deployment management and using a powerful API easier than ever.

For security and memory savings, close the Swagger when the project is released

Sawgger website

2, SpringBoot integrated Swagger

1. Build the environment

Create a new Springboot project and import the Web module and Swagger dependencies

<! -- 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>
<! -- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

Copy the code

Write a Swagger configuration class

@Configuration
@EnableSwagger2/ / open swagger2
public class SwaggerConfig {}Copy the code

testThe http://localhost:8080/swagger-ui.html page

Swagger UI: Provides a visual UI page to display the description file. The interface caller, test, project manager and so on can look up the relevant interface and make some simple interface requests in this page. The project supports online import of description files and local deployment of UI projects.

To launch the program, visit the page above:

3. Configure Swagger information

In Swagger’s configuration class:

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

import java.util.ArrayList;

@Configuration
@EnableSwagger2/ / open swagger2
public class SwaggerConfig {

    // Docket bean instance with Swagger2's core configuration, docket: The core configuration class
    @Bean
    public Docket docket(a){
        return new Docket(DocumentationType.SWAGGER_2)// Specify the API type as Swagger2
                .apiInfo(apiInfo());// Configure swagger information
    }
    // Configure the Swagger information ApiInfo
    public ApiInfo apiInfo(a){

        // Author information
        Contact contact = new Contact("A long journey."."https://mp-new.csdn.net/"."[email protected]");

        return new ApiInfo("SwaggerAPI Documentation"
                , "This document is created by Wan Ligu a Cheng, without permission, shall not be reproduced, the consequences!"
                , "1.0"
                , "https://mp-new.csdn.net/"
                , contact
                , "Apache 2.0"
                , "https://mp-new.csdn.net/"
                , newArrayList<VendorExtension>()); }}Copy the code

Start the program and view the configuration result: The configuration is successful, OK!

4. Configure the scan interface and switch

Configuration interface

Add config to Swagger config class:

package com.cheng.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;

@Configuration
@EnableSwagger2/ / open swagger2
public class SwaggerConfig {

    // Docket bean instance with Swagger2's core configuration, docket: The core configuration class
    @Bean
    public Docket docket(a){
        return new Docket(DocumentationType.SWAGGER_2)// Specify the API type as Swagger2
                .apiInfo(apiInfo())// Configure swagger information
                .enable(true)// Whether to boot swagger, true to boot false to close
                .select()
                /*RequestHandlerSelectors configure the interface scan mode as follows: BasePackage specifies the package to scan basePackage("com.cheng.controller") * any() scans all packages * None () does not scan * withClassAnnotation() Scans the annotations above the class WithClassAnnotation (RestController.class) * withMethodAnnotation() The annotation above the scan method withClassAnnotation(getMapping.class) * */
                .apis(RequestHandlerSelectors.basePackage("com.cheng.controller"))
                * ant("/user/*") : specifies the path to be scanned * any(): scans all paths * None (): does not scan all paths * regex() : scans paths that match the regular expression * */
                .paths(PathSelectors.any())
                .build();
    }
    // Configure the Swagger information ApiInfo
    public ApiInfo apiInfo(a){

        // Author information
        Contact contact = new Contact("A long journey."."https://mp-new.csdn.net/"."[email protected]");

        return new ApiInfo("SwaggerAPI Documentation"
                , "This document is created by Wan Ligu a Cheng, without permission, shall not be reproduced, the consequences!"
                , "1.0"
                , "https://mp-new.csdn.net/"
                , contact
                , "Apache 2.0"
                , "https://mp-new.csdn.net/"
                , newArrayList<VendorExtension>()); }}Copy the code

Configure the switch

.enable(true)// Whether to boot swagger, true to boot false to close
Copy the code

Interview question: How do you open up Swagger in a development environment and close it in a publishing environment

Set up a development environment application-pro.properties

server.port=8081
Copy the code

Set up a publishing environment with application-dev.properties

server.port=8082
Copy the code

Swagger Configuration:

@Bean
public Docket docket(Environment environment){

    // Set the swagger environment to use. More than one can be written
    Profiles of = Profiles.of("pro");

    // Get the project environment
    boolean flag = environment.acceptsProfiles(of);
Copy the code

Put the flag in enable()

.enable(flag)
Copy the code

Activate the publishing environment dev in the configuration file

spring-profiles-active=dev
Copy the code

Launch the program to access the Swagger-IU interface, successful access!

Then switch the environment to development environment pro

spring-profiles-active=pro
Copy the code

Launch the program to access the Swagger-IU interface, access failed!

5. Configure groups of API documents

.groupName("Thousands of miles")
Copy the code

Configure multiple groups through multiple Dockets

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

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

@Bean
public Docket docket3(a){
    return new Docket(DocumentationType.SWAGGER_2).groupName("Ink dust");
}
Copy the code

Testing:

6. Interface comments

  • @API is used on classes that indicate swagger resources. @API has two properties :value and tags

  • @apiOperation is used on methods

  • @ApiParam

    Used on methods or parameters, field description

  • @apiModel () is used on a class to describe it

  • @apiModelProperty () is used on methods and fields to indicate model properties

The use of interface annotations

@apiModel ("User help ")
public class User {

    @ApiModelProperty(" username ")
    public String username;
    @ApiModelProperty(" User password ")
    public String pwd;
}
Copy the code
// If the return value has an entity class, it will be scanned by Swagger
@apiOperation (" User's controller ")// Comment the method
@GetMapping(value = "/user")
public User user(a){
    return new User();
}

@ApiOperation(" Hello controller ")
@GetMapping(value = "/hello")// @apiparam (" user name ") annotates the parameters
public String hello(@apiparam (" username ") String username){
    return username;
}
Copy the code