一.介绍
使用 Knife4j 自动生成接口文档有以下几个好处:
1. 快速且方便:Knife4j 可以根据你的代码注解自动生成接口文档,无需手动编写和更新文档内容。这样可以节省大量时间和工作量。
2. 实时同步:当你修改了接口的代码和注解后,Knife4j 会自动重新生成接口文档,保持文档与代码的实时同步,避免了文档与代码不一致的问题。
3. 易于阅读和理解:生成的接口文档会以直观、友好的界面呈现,包括清晰的接口路径、请求方法、参数信息、响应结果等。这样团队成员、开发者和测试人员能够更轻松地阅读和理解接口的使用方式和规范。
4. 提供交互式测试功能:Knife4j 不仅可以展示接口文档,还提供了交互式的测试功能。你可以直接在页面上进行接口的测试,输入参数并查看实时响应结果,方便测试和调试。
5. 提高协作效率:通过生成接口文档,团队成员可以更方便地了解接口的定义、参数要求和返回结果,减少了沟通成本和误解的可能性,提高协作效率。
总之,使用 Knife4j 自动生成接口文档能够帮助你节省时间、提高开发效率,同时改善团队协作和沟通。它是一个方便、实用的工具,值得推荐使用。
二.如何实现
第一步
导入knife4j的springboot starter(该依赖内部已经封装了swagger和swagger-ui,所以不需要再导入swagger相关依赖)
第二步
导入完依赖,下一部当然是进行相关的配置啦~
我们新建一个config 类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Knife4j 接口文档配置
* https://doc.xiaominfo.com/knife4j/documentation/get_start.html
* @author <a href="https://gitee.com/re_lq">RE_LQ</a>
*/
@Configuration
@EnableSwagger2
@Profile({"dev", "test"})
public class Knife4jConfig {
@Bean
public Docket defaultApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(new ApiInfoBuilder()
.title("填入你想要的接口文档名称")
.description("填入你想要的描述")
.version("1.0")
.build())
.select()
// 指定 Controller 扫描包路径
.apis(RequestHandlerSelectors
.basePackage("填入你项目的controller包路径"))
.paths(PathSelectors.any())
.build();
}
}
三.可能会遇到的问题
注意,如果你使用的是Springboot 2.6.x版本及以上,那么它将与Swagger2 3.0.0版本发生冲突,运行项目将会发生报错:
org.springframework.context.ApplicationContextException:Failed to start bean 'documentationPluginsBootstrapper';nested
exception is java.lang.NullPointerException
解决办法
(1)在application.yml配置文件中添加以下配置即可解决版本冲突问题。
# 支持 swagger3
mvc:
pathmatch:
matching-strategy: ant_path_matcher
(2)降低Springboot版本到2.6以下(最笨的方法,当然也有用就对了)。
四.效果展示
启动项目,如图,输入地址:项目配置的端口号+context-path+/doc.html 即可访问自动生成的接口文档啦~