SpringDoc OpenAPI + Knife4j 使用指南
背景说明
在 Spring Boot 3.x 版本中,由于不再支持 Swagger 2,原有的 springfox-swagger2 已无法使用。为了解决接口文档管理的问题,我们需要迁移到 OpenAPI 3 规范。
本文主要解决以下问题:
- Spring Boot 3.x 下的 API 文档解决方案
- 寻找一个适合中国开发者使用习惯的 UI 界面
- 保持与原有 Swagger 2 注解的平滑迁移
相关资源
- Knife4j 官方文档:https://doc.xiaominfo.com/
- SpringDoc 官方文档:https://springdoc.org/
- OpenAPI 规范:https://swagger.io/specification/
- Spring Boot 官方文档:https://docs.spring.io/spring-boot/docs/current/reference/html/
1. Maven 依赖配置
<!-- knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.5.0</version>
</dependency>
2. 配置文件设置
application.yml
springdoc:
swagger-ui:
enabled: true
path: /swagger-ui.html
api-docs:
path: /v3/api-docs
enabled: true
packages-to-scan: com.jpruby.controller
show-actuator: true
knife4j:
enable: true
setting:
language: zh_cn
enable-swagger-models: true
enable-document-manage: true
swagger-model-name: 实体类列表
application-prod.yml(生产环境禁用)
springdoc:
api-docs:
enabled: false
swagger-ui:
enabled: false
3. 常用注解说明
控制器类注解
@Tag(name = "模块名称", description = "模块描述")
接口方法注解
// 接口描述
@Operation(summary = "接口名称", description = "接口详细描述")
// 接口响应
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "成功描述"),
@ApiResponse(responseCode = "404", description = "错误描述")
})
// 参数描述
@Parameter(description = "参数描述", required = true)
实体类注解
@Schema(description = "实体描述")
public class Entity {
@Schema(description = "属性描述")
private String field;
}
4. 使用示例
Controller 示例
@Tag(name = "用户管理", description = "用户信息的增删改查接口")
@RestController
@RequestMapping("/user")
public class UserController {
@Operation(summary = "获取用户信息", description = "根据用户ID获取用户详细信息")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "查询成功"),
@ApiResponse(responseCode = "404", description = "用户不存在")
})
@GetMapping("/{id}")
public Result getUser(
@Parameter(description = "用户ID", required = true)
@PathVariable Integer id) {
// 实现代码
}
}
Entity 示例
@Schema(description = "用户实体")
public class User {
@Schema(description = "用户ID")
private Integer id;
@Schema(description = "用户名")
private String username;
}
5. 常用注解对照表
Swagger 2 | OpenAPI 3 |
---|---|
@Api | @Tag |
@ApiOperation | @Operation |
@ApiParam | @Parameter |
@ApiModel | @Schema |
@ApiModelProperty | @Schema |
@ApiResponse | @ApiResponse |
6. 访问方式
启动应用后,可通过以下地址访问:
- Knife4j 文档:
http://localhost:8080/doc.html
- Swagger UI:
http://localhost:8080/swagger-ui.html
- OpenAPI 文档:
http://localhost:8080/v3/api-docs
7. 注意事项
- 生产环境建议关闭 Swagger UI 和 API 文档
- 注解说明要简洁明了,符合接口实际功能
- 对于敏感接口,建议添加适当的安全说明
- 确保扫描路径配置正确,避免遗漏或扫描过多
- 保持配置简单,避免不必要的配置项
- 如遇到跨域问题,需要添加相应的 CORS 配置
8. 版本信息
- Spring Boot: 3.4.1
- Knife4j: 4.5.0
- JDK: 17
9. 贡献
如果你发现任何问题或有改进建议,欢迎提交 Issue 或 Pull Request。
10. 许可证
本文档采用 Apache 2.0 License 许可证。
11. 更新日志
2024-12-31
- 初始版本
- 完成 Spring Boot 3.x 与 Knife4j 的集成
- 添加详细的配置说明和使用示例
- 优化配置项,解决跨域问题