This is the 27th day of my participation in the August More Text Challenge

Knife4j vs. Swagger-Bootstrap-UI

  1. Before rebranding Knife4j, the original name was Swagger-Bootstrap-UI. These are two different styles of UI display that change from blue to cool black mode.
  2. Knifej is written in knife4J-spring-boot-starter style. You can write configuration items in the configuration file. These configuration items provide many enhancements to better integrate SpringBoot and SpringCloud.
  3. Knifej performs updates for smoother evolution, while swagger-Bootstrap-UI has stopped more;
software Development language & framework state The final version style
Knife4j Java, JavaScript, Vue Ongoing update There is no Version 1.9.6 is blue and subsequent versions are black
swagger-bootstrap-ui Java, JavaScript, jQuery Stop more 1.9.6 blue

2. Version analysis

  1. Knife4j relies on SpringFox, so there is no need to introduce the specific version of SpringFox separately. Besides, the two versions have corresponding requirements, otherwise there will be many conflicts.
  2. To use Knife4J2.0.6 or later, the Spring Boot version must be greater than or equal to 2.2.x;
version instructions
1.9.6 Blue skin style adds more back-end modules
2.0 ~ at 2.0.5 The Ui was rewritten, the blue background changed to black, and the underlying springFox framework version was 2.9.2
2.0.6 ~ The underlying SpringFox framework version is 2.10.5, and the OpenAPI specification is V2
3.0 ~ The underlying version relies on the SpringFox framework to be upgraded to 3.0.3, and the OpenAPI specification is V3

3. Access mode

  • http://{ip}:{port}/doc.htmlIf the project is configured with interceptors, etc., you need to release the doc.html static resources

4. Springboot integration procedure

(1) Add dependencies

<! Swagger - UI Knife4j -> < swagger- UI Knife4j >
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.6}</version>
</dependency>
Copy the code

(2) Write the configuration

  • 2.0.6 and later use the @enablesWagger2webMVC annotation. Before 2.0.6 use the @enablesWagger2 annotation, which is the same as swagger-bootstrap-UI.

  • If you don’t want to write a configuration class, annotate @enablesWagger2WebMVC on the startup class to complete the entry-level integration.

package com.hanpang.config;

import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
// @enableknife4j // This annotation is not needed because it is configured in the configuration file
public class Knife4jConfig {

    @Autowired
    private Environment environment;

    @Bean
    public Docket docket(a) {
        // Set swagger environment information to display
        Profiles profiles = Profiles.of("dev"."test");
        // Determine if you are in your environment
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("Group Name")  // Configure grouping of API documents
                .enable(flag)  // Configures whether to enable Swagger
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hanpang")) // Configure the scan path
                .paths(PathSelectors.any()) // Configure what to filter
                .build();
    }
    // Basic API information
    private ApiInfo apiInfo(a) {
        return new ApiInfo("hanpang's swagger"."Test swagger - UI"."v1.0"."http://mail.qq.com".new Contact("hanpang"."http://mail.qq.com"."[email protected]"),  // Author information
                "Apache 2.0"."http://www.apache.org/licenses/LICENSE-2.0".newArrayList()); }}Copy the code

(3) Access test


The simple springboot integration with Knife4J is done, and if you don’t need enhancements, it’s done; Common Kni4j enhancements will follow!!


(4) Enable enhanced functions

Knife4j version 1.9.6 does not support enhancements; Later versions support enhancements; Knife4j 2.0.6 or later, Spring Boot must be greater than or equal to 2.2.x, and SpringFox must be the corresponding version.

(Step 1)

  • Use the @enableKnife4J annotation; Or enable knife4j enhanced mode in the configuration file knife4j.enable=true (supported only in versions 2.0.6 and later). The default is false.

(Step 2)

  • If you use personalization documents (knife4j.Documents) and personalization Settings (knife4j.setting) in the configuration file, you also need to call the extension Extesions provided by Knife4j to assign values when creating the Docket object
  • The buildExtensions method requires a grouping name to be passed in, which is intended to distinguish between the developer’s presentation under different Docket logical groups when building a custom document
package com.hanpang.config;

import java.util.ArrayList;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
@EnableKnife4j
public class Knife4jConfig {

    /* Introduce extension classes */ provided by Knife4j
    @Autowired
    private OpenApiExtensionResolver openApiExtensionResolver;

    @Autowired
    private Environment environment;

    @Bean
    public Docket docket(a) {
        // Set swagger environment information to display
        Profiles profiles = Profiles.of("dev"."test");
        // Determine if you are in your environment
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("hanpang's group")  // Configure grouping of API documents
                .enable(flag)  // Configures whether to enable Swagger
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hanpang")) // Configure the scan path
                .paths(PathSelectors.any()) // Configure what to filter
                .build()
                // In order to distinguish developers when building custom documents, different Docket logical groups are displayed separately
                .extensions(openApiExtensionResolver.buildExtensions("md"));
    }

    // Basic API information
    private ApiInfo apiInfo(a) {
        return new ApiInfo("hanpang's swagger"."Test knife4j - UI"."v1.0"."http://mail.qq.com".new Contact("dangbo"."http://mail.qq.com"."[email protected]"),  // Author information
                "Apache 2.0"."http://www.apache.org/licenses/LICENSE-2.0".newArrayList()); }}Copy the code

(5) Write the configuration

  • All the configuration items are here. If the version you are using does not take effect, it may be that the version is not supported yet. You can try to upgrade the version
  • Some enhancements also require annotations: adding author information, for example, using @apiOperationSupport and @apisupPort
  • Some enhancements have default values, such as zh_CN for i18N internationalization and true for displaying OpenAPI specifications;
  • Some enhancements do not require additional configuration in YML. Support as soon as enhancements are made, such as the ability to export offline documents and search;
knife4j:
  enable: true    # Whether to enable Knife4j enhanced mode. Default value is false
  cors: false     Whether to enable a default cross-domain configuration with a custom Host. The default value is false
  production: false     Knife4j provides BasicHttp validation for Knife4j resources to protect documents
  basic:
    enable: true       # Disable BasicHttp. Default is false
    username: dangbo    Basic user name
    password: dangbo    Password #, basic
  documents:            This property is an array
    -
      group: Md version    # Group
      name: Test Group 1    # Similar to tag in interface, grouping for custom documents
      locations: classpath:md/*     # markdown file path, either a folder (classpath:markdowns/*) or a single file (classpath:md/sign.md)
    -
      group: Markdown version
      name: Test Group 2
      locations: classpath:markdown/*
  setting:            # Personalization of the front-end Ui
    language: en-US                   # Ui default display language, currently there are two main languages: Chinese (zh-CN), English (en-us), the default is Chinese
    enableSwaggerModels: true         # Whether to display SwaggerModel function in the interface, default is true
    enableDocumentManage: true        # Whether to display the "document management" function in the interface, default is true
    swaggerModelName: List of entity classes       # Rename SwaggerModel name
    enableVersion: false              # Whether to enable the version control function for an interface. If this function is enabled, there will be small blue dots on the Ui interface after the backend changes
    enableReloadCacheParameter: false Whether to display the refresh variable button after each Debug bar
    enableAfterScript: true           AfterScript is enabled by default
    enableFilterMultipartApiMethodType: POST    The default filter type is POST
    enableFilterMultipartApis: false  If no parameter type is specified, 7 interface address types are displayed by default. If this parameter is enabled, one INTERFACE address of the Post type is displayed by default
    enableRequestCache: true          Whether to enable request parameter caching
    enableHost: false                 # whether to enable Host. Default is false
    enableHostText: 192.168. 0193.: 8000                # Host description
    enableHomeCustom: true            Whether to enable custom home page content. Default is false
    homeCustomLocation: classpath:markdown/home.md    # home content Markdown file path
    enableSearch: false             Whether to disable the search box in the Ui. The default is false
    enableFooter: false             # whether to display Footer. Default is true
    enableFooterCustom: true        Whether to enable custom Footer. Default is false
    footerCustomContent: Apache License 2.0           # Customize Footer content
    enableDynamicParameter: false   Whether to enable dynamic parameter debugging. The default value is false
    enableDebug: true               # Enable debugging. Default is true
    enableOpenApi: false            # display OpenAPI specification, default true
    enableGroup: true               # display service groups. Default is true
Copy the code

(6) verify the enhanced function (to list a few, want to try friends can see the official document)

1. Enable login

2. The default value is English

3. Customize document display