Spring Boot uses Knife4j

Knife4j

Knife4j is a framework that can provide online API documentation and is implemented based on the Swagger framework.

In a Spring Boot project, using Knife4j requires adding dependencies knife4j-spring-boot-starter:

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

Then, if you need to add configuration, create a class under the package boot-demoof the project :cn.tedu.boot.demo.configKnife4jConfig

package cn.tedu.boot.demo.config;

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 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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
    
    

    /**
     * 【重要】指定Controller包路径
     */
    private String basePackage = "cn.tedu.boot.demo.controller";
    /**
     * 分组名称
     */
    private String groupName = "product";
    /**
     * 主机名
     */
    private String host = "http://java.tedu.cn";
    /**
     * 标题
     */
    private String title = "酷鲨商城在线API文档--商品管理";
    /**
     * 简介
     */
    private String description = "酷鲨商城在线API文档--商品管理";
    /**
     * 服务条款URL
     */
    private String termsOfServiceUrl = "http://www.apache.org/licenses/LICENSE-2.0";
    /**
     * 联系人
     */
    private String contactName = "Java教学研发部";
    /**
     * 联系网址
     */
    private String contactUrl = "http://java.tedu.cn";
    /**
     * 联系邮箱
     */
    private String contactEmail = "[email protected]";
    /**
     * 版本号
     */
    private String version = "1.0.0";

    @Autowired
    private OpenApiExtensionResolver openApiExtensionResolver;

    @Bean
    public Docket docket() {
    
    
        String groupName = "1.0.0";
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .host(host)
                .apiInfo(apiInfo())
                .groupName(groupName)
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build()
                .extensions(openApiExtensionResolver.buildExtensions(groupName));
        return docket;
    }

    private ApiInfo apiInfo() {
    
    
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .termsOfServiceUrl(termsOfServiceUrl)
                .contact(new Contact(contactName, contactUrl, contactEmail))
                .version(version)
                .build();
    }

}

Note: The package name in the above configuration must be modified to ensure that it is the package where the controller class in the current project is located! Other items can not be modified, the above configuration code can be found from Knife4j's official website!

Finally, you also need to enable the enhanced mode of Knife4j in the configuration file:

# Knife4j配置
knife4j:
  # 是否开启增强模式
  enable: true

After completion, start the project and visit http://localhost:8080/doc.html in the browser to view the API documentation of the current project.

Add annotations to the controller class @Apiand configure tagsattributes to specify the module name, for example:

@Api(tags = "管理员管理模块")  // 新增
@RestController
@RequestMapping(value = "/admins", produces = "application/json; charset=utf-8")
public class AdminController {
    
    
    
    // ===== 原有其它代码 =====
    
}

Adding annotations to the method of processing requests @ApiOperationcan configure the business name, for example:

@ApiOperation("管理员登录") // 新增
@PostMapping("/login")
public JsonResult<AdminSimpleVO> login(@Validated AdminLoginDTO adminLoginDTO) {
    
    
    AdminSimpleVO adminSimpleVO = adminService.login(adminLoginDTO);
    return JsonResult.ok(adminSimpleVO);
}

When it is necessary to specify the display order of each business in the API document, you can add annotations to the method of processing the request @ApiOperationSupport, configure the attributes of this annotation order, and finally when displaying the API documents, they will be orderarranged in ascending order according to the attribute values, for example:

@ApiOperation("管理员登录")
@ApiOperationSupport(order = 900) // 新增
@PostMapping("/login")
public JsonResult<AdminSimpleVO> login(@Validated AdminLoginDTO adminLoginDTO) {
    
    
    AdminSimpleVO adminSimpleVO = adminService.login(adminLoginDTO);
    return JsonResult.ok(adminSimpleVO);
}

Generally, it is recommended that the value configured above ordershould be at least 2 digits, and there is a reserved space, for example, the services between 10 and 19 are all services for adding data, the services between 20 and 29 are all services for deleting data, and the services between 30 and 39 are all services for deleting data. It is a business of modifying data, and between 40 and 49 is a business of querying data.

If the parameter of the method of the controller processing the request is a custom encapsulation type, you can add it to the property of the encapsulation type to @ApiModelPropertyconfigure the display of the parameter in the document, for example:

package cn.tedu.boot.demo.pojo.dto;


import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Data
public class AdminLoginDTO implements Serializable {
    
    

    @ApiModelProperty(value = "用户名") // 配置参数名
    private String username;

    @ApiModelProperty("密码") // 配置参数名
    private String password;

}

In @ApiModelPropertyaddition to configuring the name of the parameter displayed in the API document, you can also configure whether it is necessary, for example:

@ApiModelProperty(value = "用户名", required = true)

In addition, you can also configure the parameter type, etc., but it is not necessary to configure, and usually the framework can automatically recognize it normally.

For some attributes whose names may be special (ordinary people can’t directly understand them), or attributes with clear normative requirements for values ​​(for example, some values ​​are 0 or 1), examples can be listed so that people who view API documents can Reference, for example:

@ApiModelProperty(value = "用户名", required = true, example = "admin")

In addition to configuring request parameters, this attribute can also be used to respond to the type of result, for example:

public class JsonResult<T> implements Serializable {
    
    


    @ApiModelProperty("业务状态码")
    private Integer state;

    @ApiModelProperty("消息")
    private String message;

    @ApiModelProperty("数据")
    private T data;
    
    // ......

If the above private T data;actual values ​​also need to add descriptions, just continue to use the configuration on the properties of the corresponding class @ApiModelProperty! Note: dataThe attribute here can be of any data type, and must be declared as generic, Objectotherwise it will not be able to apply @ApiModelPropertythe configuration.

In addition, when added to the response type attribute, the attribute can also be @ApiModelPropertyconfigured in the annotation positionto set the display order of each attribute in the response JSON, for example:

@ApiModelProperty(value = "业务状态码", position = 5)

Guess you like

Origin blog.csdn.net/gezongbo/article/details/126264104