What components do programmers like to use now to write interface documents? Swagger has fallen behind, knife4j is the kingly way, it is very cool to use, teach you a few simple steps to integrate knife4j with springboot, do not do redundant things

As a programmer, writing interface documents is a long-standing and difficult problem. To configure access paths, request methods, request parameters, request lists, request parameter instances, return results, return result types, return structures, etc., just think about it.

We used to like to use swagger, but later we used swagger-bootstrap-ui, and then we used YAPI. YAPI really makes people feel better. We agree with it.

Later, I came into contact with knife4j, which is easy to use. In the process of writing code, not only interface documents are generated, but also Html/Markdown/Word/pdf can be downloaded offline, and it can also support the setting of login account and password, which is really cool.

Comparison between swagger and knife4j

Compare items knife4j swagger
Debug Support Support
Export word Support Not support
Export pdf Support

not support,

but can be exported with a browser

Export html Support

not support,

but can be exported with a browser

Export Markdown Supported Not Supported
Authentication Supported Not Supported
Document Management Supported Not supported

one-click copy

(interface, address, documentation)

Support Not Support
Switch Configuration Support Support

Without further ado, let’s take a look at springboot’s integration of knife4j.

1. Introduce dependencies

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

2. Write Configuration configuration

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @Copyright:
 * @Author:<a href=":@qq.com"></a>
 * @Description
 * @Created by 2023/5/18 17:11
 */
@Configuration
@EnableKnife4j
@EnableSwagger2
public class Knife4jConfiguration {
}

3. Write WebMvcConfigurationSupport interceptor release configuration

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @Copyright:
 * @Author:<a href=""></a>
 * @Description
 * @Created by 2023/5/18 18:13
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
  }
}

4. File application.properties configuration

#Enable knife4j enhanced mode
knife4j.enable=true
#Production mode shielding, true will prohibit access to API online documents, false can see documents, password invalid
knife4j.production=false
#Basic authentication function, that is, whether you need to pass the user name and password verification before you can access the online API document
knife4j.basic.enable=true
#If the Basic authentication is enabled but the user name and password are not configured, the default is: admin/123321, even if the input is correct, it will continue to loop
knife4j.basic.username=root
knife4j.basic.password=root
#In order to save traffic, when returning data, the configuration does not return data whose attribute value is null
spring.jackson.default-property-inclusion=non_null

5. The controller class uses annotations to write interfaces

import com.example.zhoupingcommon.norepeated.NoRepeatedSubmit;
import com.example.zhoupingcommon.response.ResponseResult;
import com.ping.hui.com.Test.ScrewConfig.ScrewConfig;
import com.ping.hui.com.Test.ScrewConfig.TestDto;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Description
 * @Author zhouping
 * @Date 0:08 2022/4/22
 **/
@RestController
@RequestMapping("/api")
public class Test {
    @Autowired
    private ScrewConfig screwConfig;

    @GetMapping("test")
    @NoRepeatedSubmit
    public void test() {
        screwConfig. documentGeneration();
    }

    @PostMapping("testPost")
    @NoRepeatedSubmit
    @ApiImplicitParams({
            @ApiImplicitParam(name = "str", value = "the first parameter", dataType = "String", required = true),
            @ApiImplicitParam(name = "two", value = "the second parameter", required = true)
    })
    public ResponseResult testPost(@RequestParam("str") String str, @RequestParam("two") String two) {
        return ResponseResult. success();
    }

    @PostMapping("testPostBody")
    @NoRepeatedSubmit
    @ApiImplicitParams({
            @ApiImplicitParam(name = "str", value = "the first parameter", dataType = "String", required = true),
            @ApiImplicitParam(name = "two", value = "the second parameter", required = true)
    })
    public ResponseResult testPostBody(TestDto testDto) {
        return ResponseResult. success();
    }
}

Knowledge expansion:

In the process of using knife4j, swagger annotations can be used to mark documents. The annotations are organized as follows:

@Api:

Added on the controller class, the module name can be configured through the tags attribute of this annotation, and a number can be added before each module name, and it will be arranged in ascending order according to this name (the number in front of the name)

@ApiOperation: Added to the method of processing the request, the business name can be configured through the value attribute of this annotation

@ApiOperationSupport: Added to the request processing method, the order attribute of this annotation can be used to configure the sorting of each business, and finally will be arranged in ascending order according to the value of the order attribute (int type)

@ApiModelProperty: Added to the POJO type property, the description text of the request parameter can be configured through the value attribute of this annotation, and whether this parameter must be submitted can be configured through the required attribute of this annotation (note: this configuration does not have the checking function), the example value can be configured through the example attribute of this annotation

@ApiImplicitParam: Added to the method of processing the request, the name attribute of this annotation indicates which request parameter you need to configure the method, and the description text of the request parameter is configured through the value attribute of this annotation, through this annotation The required attribute can configure whether this parameter must be submitted, configure the data type of the request parameter through the dataType attribute of this annotation, and configure the example value through the example attribute of this annotation

@ApiImplicitParams: Added to the method of processing the request, when there are multiple request parameters that are configured through @ApiImplicitParam, multiple @ApiImplicitParam configurations should be used as the parameter value of the current annotation

6. Look at the results:

1) Visit the address http://127.0.0.1:8002/doc.html and log in. The account password is the account password set in the application.properties file

2) Go to the homepage

3) If you want to export documents, you can open Document Management – Offline Documents, which supports pdf, word, html, Markdown

4) Interface documentation, swagger-based documentation