The reason
Interface document must be a nightmare for many development partners, not only to write detailed, but also timely maintenance of the document and back-end code to keep consistent, a little not timely update the interface document, front-end students will certainly complain that back-end students to the document is inconsistent with the actual situation.
Therefore, Swagger component is introduced, which realizes the code is the document, the back-end just write the code, only need to pass a few annotations, will automatically generate interface documents, front-end students can access online.
However, front-end students with aesthetic requirements for the interface ridicule Swagger native interface is too low, and few features.
There is oppression, there is resistance, the back end must not accept, since you dislike native Swagger too low, then give you open super VIP-KNIfe4J.
Native Swagger
Springboot integration with Swagger is simple, using a few common annotations. Since there are many people who have never used Swagger in an interview, here is a brief introduction to Swagger.
Firstly, Swagger dependency is introduced in Spingboot project, mainly 2, as follows:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
Copy the code
Write Swagger configuration class, the name of the configuration item is easy to understand, you can modify the configuration according to your own situation, note that the apis method specifies the package path to scan, you must write your own project.
package com.nobody.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Value("${swagger.enable:true}")
private boolean swaggerEnable;
@Bean
public Docket createApi(a) {
// Global parameters
List<Parameter> pars = new ArrayList<>();
return new Docket(DocumentationType.SWAGGER_2).enable(swaggerEnable).apiInfo(apiInfo())
.select().apis(RequestHandlerSelectors.basePackage("com.nobody"))
.paths(PathSelectors.any()).build().globalOperationParameters(pars);
}
private ApiInfo apiInfo(a) {
return new ApiInfoBuilder().title("XX Service back-end API").description("XX service special API, other systems do not call!")
.version("1.0").termsOfServiceUrl("https://nobody.com")
.contact(new Contact("Orange"."https://nobody.com"."[email protected]")).build(); }}Copy the code
Here are some common annotations and how to use them. See the official documentation for more annotations and detailed usage.
- @Api: Applies to a class to indicate that this class is Swagger’s resource.
- @apiOperation: mainly used on methods to describe an interface.
- @apiparam: used on methods, parameters, and fields to specify parameters.
- @ApiModel: Applies to classes. This parameter is used when interface parameters are used to describe entity classes.
- @APIModelProperty: Applies to methods and fields, generally used for attribute specification of entity classes.
package com.nobody.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/ * * *@Description
* @Author Mr.nobody
* @Date 2021/3/28
* @Version1.0 * /
@apiModel (value = "admin entity ")
@Data
public class AdminDTO {
@APIModelProperty (value = "user ID", Required = true, example =" 1548w4DWF7AS1a21cv4 ")
private String personId;
@apiModelProperty (value = "username ", example =" tangerine ")
private String name;
@apiModelProperty (value = "user age ", Required = true, example = "18")
private Integer age;
}
Copy the code
package com.nobody.controller;
import com.nobody.dto.AdminDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/ * * *@Description
* @Author Mr.nobody
* @Date 2021/3/27
* @Version1.0 * /
@API (tags = {" Admin related "})
@RestController
@RequestMapping("admin")
public class AdminController {
@apiOperation (value = "add administrator ", notes =" Only an administrator can add administrators ", Produces = "application/json", Consumes = "application/json")
@PostMapping("add")
public AdminDTO add(@apiParam (value = "parameter body ", Required = true) @RequestBody AdminDTO adminDTO) {
return adminDTO;
}
@APIOperation (value = "Administrator list ", notes =" Notice: Only administrator can get administrator list ", produces = "application/json")
@GetMapping("list")
public List<AdminDTO> list(
@apiparam (value = "page number from 1, 1, 2, 3..." , required = true, example = "1") @RequestParam Integer pageIndex,
@apiParam (value = "page size ", Required = true, example = "10") @apiparam (value =" page size ", Required = true, example = "10") @RequestParam Integer pageSize) {
return newArrayList<>(); }}Copy the code
Knife4J
Knife4j’s predecessor was Swagger-Bootstrap-UI, and the predecessor swagger-Bootstrap-UI was a UI skin project of pure Swagger-UI.
The current Knife4j release already has SpringFox in it, so we don’t need to introduce a specific version of SpringFox separately, which would cause version conflicts.
Note that with Knife4j2.0.6 and later, the SpringBoot version must be at least 2.2.x.
Knife4J is extremely simple to use because Knife4J encapsulates it as an starter, a pluggable component that only needs to be used by introducing the starter dependency.
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
Copy the code
However, the Swagger configuration class is exactly the same as the native class, namely the Swagger2Config class introduced above. Only after the project starts, the interface document interface access address is different:
- Native Swagger: http://ip:port/swagger-ui.html#/
- Knife4J: http://ip:port/doc.html#/
Is the interface much better than the original, or keep it simple and beautiful, but with more features?
When we Open an interface, the display interface is more complete and divided into three pages, Documentation, Debug and Open, as shown below:
Support global search, do not need to search in many interfaces one by one, save time.
Knife4j provides the Debug function for global parameters. Currently, by default, Knife4j provides header and Query (form) inputs. After global parameters are added, they are displayed on the Debug TAB page by default.
Four formats offline Knife4j provide export documents (Html/Markdown/Word/OpenAPI)
After personalized configuration is enabled, you need to close the Tab Tab and then open it again or refresh the current page.
See the official documentation for more details on Knife4J. Xiaoym. Gitee. IO/knife4j/doc…