SpringBoot 整合 Knife4j——接口文档自动生成最佳实践
·
接口文档是前后端协作的桥梁。手写文档费时且容易和代码不一致,Knife4j 可以自动从注解生成接口文档,提供在线调试功能。
一、为什么选 Knife4j
| 对比 | Knife4j | Swagger 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 即可看到接口文档页面。
💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!
更多推荐



所有评论(0)