SpringBoot integrates Swagger3

Foreword

This article will introduce the integration process of the API visualization framework Swagger in the SpringBoot framework and a series of tests for Swagger3.

Development background

If the project is developed using a method of separating front-end and back-end, the development of front-end and back-end code requires developers to divide labor and collaborate, as well as conduct joint debugging of front-end and back-end. The development interface must be standardized during development. The writing of interface documents is usually completed by back-end developers. The interface document contains five parts: interface description, request URL, request parameters, request method, and response data description. But manually writing interface documents is very tricky, so next we can use Swagger to write interface documents.

What is Swagger? (official website)

Swagger is the world’s largest OpenAPI Specification (OAS) API development tool framework, supporting the development of the entire API life cycle from design and documentation to testing and deployment. Swagger is a tool that is used to create standardized files for server connections and can conduct docking tests.

spring boot integrated swagger3 version

  • Introduce pom.xml dependency

     <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-boot-starter</artifactId>
                <version>3.0.0</version>
            </dependency>
            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-spring-boot-starter</artifactId>
                <version>3.0.3</version>
            </dependency>
    
  • Add swagger3.0 configuration

package com.weh.config;

import com.google.common.collect.Sets;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;

@Configuration
@EnableOpenApi //Note: This annotation is the key point
public class SwaggerConfig {<!-- -->
    /**
     * The upper part of the API page displays information
     */
    private ApiInfo apiInfo() {<!-- -->
        return new ApiInfoBuilder()
                .title("Api Doc")
                .description("SpringFox 3.0.0 released: https://www.xx.xx/swagger-ui/index.html")
                .contact(new Contact("weh", null, "xxxxx"))
                .version(
                        "Application Version: "
                                 + "1.0.0"
                                 + ", Spring Boot Version: "
                                 + SpringBootVersion.getVersion())
                .build();
    }

    @Bean
    public Docket createRestApi() {<!-- -->
        return new Docket(DocumentationType.OAS_30)
                .pathMapping("/")
                // Define whether to enable swagger, false means closed, which can be controlled through variables
                .enable(true)
                // Set the api's meta information to be included in the json ResourceListing response.
                .apiInfo(apiInfo())
                //Interface debugging address
                .host("http://localhost:9098")
                //Select which interfaces to publish as swagger's doc
                .select()
                //Key part: Path to scan the package
                .apis(RequestHandlerSelectors.basePackage("com.weh.controller"))
                .paths(PathSelectors.any())
                .build()
                //Supported communication protocol collection
                .protocols(Sets.newHashSet("http", "https"))
                // Authorization information settings, necessary header token and other authentication information
                .securitySchemes(securitySchemes())
                //Authorization information global application
                .securityContexts(securityContexts());
    }

    /**
     *Set authorization information
     */
    private List securitySchemes() {<!-- -->
        ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }

    /**
     * Global application of authorization information
     */
    private List securityContexts() {<!-- -->
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(
                                Collections.singletonList(
                                        new SecurityReference(
                                                "BASE_TOKEN",
                                                new AuthorizationScope[]{<!-- -->new AuthorizationScope("global", "")})))
                        .build());
    }

    public void addInterceptors(InterceptorRegistry registry) {<!-- -->
        try {<!-- -->
            Field registrationsField =
                    FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
            List<InterceptorRegistration> registrations =
                    (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
            if (registrations != null) {<!-- -->
                for (InterceptorRegistration interceptorRegistration : registrations) {<!-- -->
                    interceptorRegistration
                            .excludePathPatterns("/swagger**/**")
                            .excludePathPatterns("/webjars/**")
                            .excludePathPatterns("/v3/**")
                            .excludePathPatterns("/doc.html");
                }
            }
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
        }
    }
}

  • # Application service WEB access port
    server:
      port: 9098
    
  • overall framework

Visit URL: http://localhost:9098/doc.html
Page display results: