SpringBoot integrates Swagger3, hurry up!

Article directory

  • 1. What is Swagger?
  • 2. Usage steps
    • 1.Introduce swagger3 dependency
    • 2. Add swagger.conf configuration class
    • 3. Add application.yml configuration
    • 4. Check whether the integration is successful
    • 5.Commonly used annotations
    • 6.swagger beautification
  • Summarize

1. What is Swagger?

Swagger is a standardized and complete framework for generating, describing, invoking, and visualizing RESTful-style web services.

The overall goal is to have the client and file system update at the same speed as the server. File methods, parameters, and models are tightly integrated into server-side code, allowing the API to always stay in sync. Swagger makes deployment management and using powerful APIs easier than ever.

2. Usage steps

1.Introduce swagger3 dependency

code show as below:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2. Add swagger.conf configuration class

code show as below:

package com.uhu.swagger;


import io.swagger.models.auth.In;
import liquibase.repackaged.org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
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.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.springframework.context.annotation.Configuration;

/**
 * @author liujunjie
 * @description swagger configuration
 * @create 2023-11-06 15:16
 **/
@Configuration
// Declare to open swagger2
@EnableOpenApi
public class SwaggerConfig implements WebMvcConfigurer {<!-- -->

    /**
     * Whether to enable swagger
     */
    @Value("${uhu.swagger.enable}")
    private Boolean enable;

    /**
     * title
     */
    @Value("${uhu.swagger.title}")
    private String title;

    /**
     * Version
     */
    @Value("${uhu.swagger.version}")
    private String version;

    /**
     * describe
     */
    @Value("${uhu.swagger.description}")
    private String description;

    /**
     * Scanned packages
     */

    @Value("${uhu.swagger.scanPackage}")
    private String scanPackage;

    /**
     *Interface debugging address
     */
    @Value("${uhu.swagger.host}")
    private String host;

    @Bean
    Docket api() {<!-- -->
        //Basic API configuration of springfox
        return new Docket(DocumentationType.OAS_30)
                // Treat the mapped path as base Path and add it to apis
                .pathMapping("/")
                // Define whether to enable swagger, false means closed, which can be controlled through variables
                .enable(enable)

                // Set the api's meta information to be included in the json ResourceListing response.
                .apiInfo(apiInfo())

                //Interface debugging address
                .host(host)

                //Select which interfaces to publish as swagger's doc
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()

                //Supported communication protocol collection
                .protocols(new HashSet<>(Arrays.asList("http", "https")))

                // Authorization information settings, necessary header token and other authentication information
                .securitySchemes(Collections.singletonList(new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue())))

                //Authorization information global application
                .securityContexts(Collections.singletonList(
                        SecurityContext.builder()
                                .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{<!-- -->new AuthorizationScope("global", "")})))
                                .build()
                ));
    }

    /**
     * The upper part of the API page displays information
     */
    private ApiInfo apiInfo() {<!-- -->
        return new ApiInfoBuilder().title(title + " Api Doc")
                .description(description)
                .contact(new Contact("xxx", null, "[email protected]"))
                .version(version)
                .build();
    }

    /**
     * Universal interceptor excludes swagger settings, all interceptors will automatically add swagger-related resource exclusion information
     */
    @SuppressWarnings("unchecked")
    @Override
    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();
        }
    }

}


3. Add application.yml configuration

code show as below:

uhu:
  swagger:
    enable: true
    title: ${<!-- -->spring.application.name}
    version: 1.0.0
    description: Enterprise compliance management system interface document
    scanPackage: com.uhu
    host: http://localhost:${<!-- -->server.port}

4. Check whether the integration is successful

Start the project and visit http://localhost:port/context-path/swagger-ui.html

5. Commonly used annotations

Annotation Annotation Description Usage
@Api Class annotation, used to alias the controller
@ApiOperation Commonly used to describe methods
@ApiModel and @ApiModelProperty Description request response description
@ApiParam Path Parameter annotations
@ ApiImplicitParam and @ApiImplicitParams Describe method parameters

6.swagger beautification

Add beautification dependency

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

Add yml configuration

knife4j:
  enable: true
  basic:
    enable: true
    username:admin
    password:admin
  setting:
    language: zh-CN

Restart service
Visit http://localhost:port/context-path/doc.html

Summary

By integrating Swagger3, we can easily generate interface documents, making front-end and back-end development collaboration more efficient. The pages beautified through knife4j are more suitable for Chinese people’s reading habits.
The above is how SpringBoot integrates Swagger3. Isn’t it very simple? Let’s use it quickly! ! !