Knife4j 接口文档工具
2025/7/14大约 5 分钟
Knife4j 接口文档工具完整教程
前置知识
在开始本教程之前,建议您具备以下基础知识:
- Spring Boot 基础
- Maven 或 Gradle 构建工具
- RESTful API 设计基础
- Swagger 基本概念
什么是 Knife4j?
Knife4j 是一个基于 Swagger 的增强 UI 工具,为 Java 开发者提供了更美观、更强大的 API 文档界面。它基于 OpenAPI 3.0 规范,提供了:
- 🎨 美观的界面:基于 Vue 3 + Ant Design Vue 的现代化界面
- 🔧 增强功能:支持接口调试、文档导出、Mock 数据等
- 📱 响应式设计:支持移动端访问
- 🚀 高性能:基于 Spring Boot 2.x/3.x 的高性能实现
Knife4j vs Swagger UI
特性 | Knife4j | Swagger UI |
---|---|---|
界面美观度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
功能丰富度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
中文支持 | ⭐⭐⭐⭐⭐ | ⭐⭐ |
性能 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
环境准备
1. 添加依赖
在您的 pom.xml
中添加 Knife4j 依赖:
<dependencies>
<!-- Knife4j 核心依赖 -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
<!-- Spring Boot Web 启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2. 基础配置
在 application.yml
中添加基础配置:
# Knife4j 配置
knife4j:
enable: true # 启用 Knife4j
setting:
language: zh-CN # 界面语言
enable-swagger-models: true # 启用模型
enable-document-manage: true # 启用文档管理
swagger-model-name: 实体类列表 # 模型名称
enable-version: false # 禁用版本控制
enable-reload-cache-parameter: false # 禁用重载缓存
enable-after-script: true # 启用后置脚本
enable-filter-multipart-api-method-type: POST # 过滤文件上传接口
enable-filter-multipart-apis: false # 禁用文件上传接口过滤
enable-request-cache: true # 启用请求缓存
enable-host: false # 禁用主机
enable-host-text: "" # 主机文本
enable-home-custom: false # 禁用首页自定义
home-custom-path: "" # 首页自定义路径
enable-search: true # 启用搜索
enable-footer: false # 禁用页脚
enable-footer-custom: false # 禁用页脚自定义
footer-custom-content: "" # 页脚自定义内容
enable-dynamic-parameter: false # 禁用动态参数
enable-debug: true # 启用调试
enable-open-api: false # 禁用 OpenAPI
enable-group: true # 启用分组
核心配置
1. Knife4j 配置类
package com.example.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class Knife4jConfig {
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("用户管理系统 API")
.description("基于 Spring Boot + Knife4j 的用户管理系统接口文档")
.version("1.0.0")
.contact(new Contact()
.name("开发团队")
.email("dev@example.com")
.url("https://github.com/example"))
.license(new License()
.name("MIT License")
.url("https://opensource.org/licenses/MIT")));
}
}
2. 控制器示例
package com.example.controller;
import com.example.model.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@Tag(name = "用户管理", description = "用户相关的增删改查接口")
@RestController
@RequestMapping("/api/users")
public class UserController {
@Operation(summary = "获取用户信息", description = "根据用户ID获取用户详细信息")
@ApiResponse(responseCode = "200", description = "成功获取用户信息",
content = @Content(schema = @Schema(implementation = User.class)))
@ApiResponse(responseCode = "404", description = "用户不存在")
@GetMapping("/{id}")
public User getUserById(
@Parameter(description = "用户ID", required = true, example = "1")
@PathVariable Long id) {
// 模拟返回用户数据
return new User(id, "张三", "zhangsan@example.com");
}
@Operation(summary = "创建用户", description = "创建新用户")
@PostMapping
public Map<String, Object> createUser(
@Parameter(description = "用户信息", required = true)
@RequestBody User user) {
Map<String, Object> result = new HashMap<>();
result.put("message", "用户创建成功");
result.put("userId", 1L);
return result;
}
}
3. 实体类示例
package com.example.model;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Schema(description = "用户实体")
public class User {
@Schema(description = "用户ID", example = "1")
private Long id;
@Schema(description = "用户名", example = "张三", required = true)
private String name;
@Schema(description = "邮箱地址", example = "zhangsan@example.com")
private String email;
}
高级功能
1. 接口分组
@Tag(name = "用户管理", description = "用户相关的增删改查接口")
@RestController
@RequestMapping("/api/users")
public class UserController {
// 用户相关接口
}
@Tag(name = "订单管理", description = "订单相关的增删改查接口")
@RestController
@RequestMapping("/api/orders")
public class OrderController {
// 订单相关接口
}
2. 参数验证
@Operation(summary = "更新用户信息")
@PutMapping("/{id}")
public User updateUser(
@Parameter(description = "用户ID", required = true)
@PathVariable Long id,
@Parameter(description = "用户信息", required = true)
@Valid @RequestBody User user) {
// 更新用户逻辑
return user;
}
3. 文件上传
@Operation(summary = "上传用户头像")
@PostMapping("/{id}/avatar")
public Map<String, String> uploadAvatar(
@Parameter(description = "用户ID")
@PathVariable Long id,
@Parameter(description = "头像文件")
@RequestParam("file") MultipartFile file) {
Map<String, String> result = new HashMap<>();
result.put("message", "头像上传成功");
result.put("fileName", file.getOriginalFilename());
return result;
}
最佳实践
安全注意事项
- 生产环境:生产环境中建议关闭 Knife4j 或限制访问
- 敏感信息:不要在接口文档中暴露敏感信息
- 权限控制:对文档访问进行权限控制
性能优化
- 缓存配置:合理配置缓存参数
- 分组管理:按模块进行接口分组
- 文档精简:避免在文档中包含过多无用信息
1. 生产环境配置
# 生产环境配置
knife4j:
enable: false # 生产环境关闭
setting:
enable-debug: false # 关闭调试模式
2. 开发环境配置
# 开发环境配置
knife4j:
enable: true
setting:
enable-debug: true
enable-search: true
language: zh-CN
常见问题
1. 如何自定义 Knife4j 界面?
可以通过配置文件自定义界面样式和内容:
knife4j:
setting:
enable-home-custom: true
home-custom-path: classpath:markdown/home.md
enable-footer-custom: true
footer-custom-content: "© 2024 开发团队"
2. 如何导出接口文档?
Knife4j 支持多种格式的文档导出:
- HTML 格式
- Word 格式
- PDF 格式
- Markdown 格式
在 Knife4j 界面右上角可以找到导出按钮。
3. 如何处理复杂的请求参数?
对于复杂的请求参数,可以使用 @Schema
注解进行详细描述:
@Schema(description = "分页查询参数")
public class PageRequest {
@Schema(description = "页码", example = "1", defaultValue = "1")
private Integer page = 1;
@Schema(description = "每页大小", example = "10", defaultValue = "10")
private Integer size = 10;
@Schema(description = "排序字段", example = "createTime")
private String sortBy;
}
总结
本教程详细介绍了 Knife4j 的完整使用流程,包括:
- ✅ 环境准备:添加必要的依赖和基础配置
- ✅ 核心配置:配置类和控制器示例
- ✅ 高级功能:接口分组、参数验证、文件上传
- ✅ 最佳实践:安全注意事项和性能优化
- ✅ 常见问题:自定义界面、文档导出、复杂参数处理
下一步学习
- 学习 Spring Security 集成 Knife4j
- 了解微服务架构中的文档管理
- 探索 Knife4j 的高级特性(如 Mock 数据)
希望这个教程对您有所帮助!如果您有任何问题,欢迎在评论区讨论。