java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot Knife4j接口文档自动生成

SpringBoot整合Knife4j实现接口文档自动生成的最佳实践

作者:张老师技术栈

接口文档是前后端协作的桥梁,手写文档费时且容易和代码不一致,Knife4j 可以自动从注解生成接口文档,提供在线调试功能,本文给大家介绍了SpringBoot整合Knife4j实现接口文档自动生成的最佳实践,需要的朋友可以参考下

接口文档是前后端协作的桥梁。手写文档费时且容易和代码不一致,Knife4j 可以自动从注解生成接口文档,提供在线调试功能。

一、为什么选 Knife4j

对比Knife4jSwagger UI手写文档
UI 美观度⭐⭐⭐⭐⭐ 中文友好⭐⭐⭐ 英文原生⭐⭐⭐
在线调试✅ 支持✅ 支持
代码侵入低(注解)低(注解)无(但费时)
维护成本自动同步自动同步⭐⭐⭐ 极高

二、集成 Knife4j

1. 引入依赖

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

2. 配置

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
knife4j:
  enable: true
  setting:
    language: zh-CN
    enable-swagger-models: true
    enable-document-manage: true
    swagger-model-order: 1

3. 配置类

@Configuration
@EnableKnife4j
public class Knife4jConfig {

    @Bean
    public Docket defaultApi() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.zhang"))
            .paths(PathSelectors.any())
            .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("秒杀系统接口文档")
            .description("电商秒杀系统 RESTful API")
            .version("V1.0")
            .contact(new Contact("张政", "", ""))
            .build();
    }
}

访问 http://localhost:9090/doc.html 即可看到接口文档页面。

到此这篇关于SpringBoot整合Knife4j实现接口文档自动生成的最佳实践的文章就介绍到这了,更多相关SpringBoot Knife4j接口文档自动生成内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文