RuoYiSwagger集成:API文档自动生成
2026-02-04 04:45:54作者:劳婵绚Shirley
还在为手动编写API文档而烦恼?还在为接口变更导致文档不同步而头疼?RuoYi框架内置的Swagger集成功能,让API文档自动生成变得简单高效。本文将深入解析RuoYi中Swagger的完整集成方案,助你实现零配置的API文档自动化管理。
📋 文章导读
通过本文,你将掌握:
- Swagger在RuoYi中的完整配置流程
- 常用注解的使用方法和最佳实践
- 权限控制与Swagger的完美结合
- 生产环境的安全部署策略
- 常见问题排查与性能优化技巧
🚀 Swagger集成概述
Swagger(现称OpenAPI)是一个强大的API文档生成工具,RuoYi框架基于Springfox实现了Swagger 3.0的深度集成。通过简单的配置和注解,即可自动生成美观、交互式的API文档。
技术架构图
graph TB
A[Spring Boot Application] --> B[Swagger Config]
B --> C[API扫描配置]
C --> D[注解解析]
D --> E[文档生成]
E --> F[Swagger UI]
F --> G[开发者访问]
H[Controller层] --> I[@Api注解]
H --> J[@ApiOperation注解]
H --> K[@ApiImplicitParam注解]
L[Entity层] --> M[@ApiModel注解]
L --> N[@ApiModelProperty注解]
🔧 核心配置详解
1. Maven依赖配置
RuoYi在父pom.xml中统一管理Swagger依赖版本:
<!-- Swagger3依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 防止类型转换错误,手动指定版本 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.2</version>
</dependency>
2. Swagger配置类
RuoYi提供了完整的Swagger配置类,支持灵活的API扫描策略:
@Configuration
public class SwaggerConfig {
@Value("${swagger.enabled}")
private boolean enabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.enable(enabled) // 动态控制开关
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("若依管理系统_接口文档")
.description("用于管理集团旗下公司的人员信息")
.contact(new Contact(RuoYiConfig.getName(), null, null))
.version("版本号:" + RuoYiConfig.getVersion())
.build();
}
}
3. 配置文件设置
在application.yml中配置Swagger开关:
# Swagger配置
swagger:
# 是否开启swagger
enabled: true
🎯 注解使用指南
控制器层注解
@Api - 控制器分组
@Api(tags = "用户信息管理")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController {
// 控制器代码
}
@ApiOperation - 接口描述
@ApiOperation("获取用户列表")
@GetMapping("/list")
public R<List<UserEntity>> userList() {
// 业务逻辑
}
@ApiImplicitParam - 参数说明
@ApiOperation("获取用户详细")
@ApiImplicitParam(
name = "userId",
value = "用户ID",
required = true,
dataType = "int",
paramType = "path"
)
@GetMapping("/{userId}")
public R<UserEntity> getUser(@PathVariable Integer userId) {
// 业务逻辑
}
@ApiImplicitParams - 多参数说明
@ApiOperation("新增用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer"),
@ApiImplicitParam(name = "username", value = "用户名称", dataType = "String"),
@ApiImplicitParam(name = "password", value = "用户密码", dataType = "String"),
@ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String")
})
@PostMapping("/save")
public R<String> save(UserEntity user) {
// 业务逻辑
}
实体层注解
@ApiModel - 模型说明
@ApiModel(value = "UserEntity", description = "用户实体")
class UserEntity {
// 实体字段
}
@ApiModelProperty - 字段说明
@ApiModelProperty("用户ID")
private Integer userId;
@ApiModelProperty("用户名称")
private String username;
@ApiModelProperty("用户密码")
private String password;
@ApiModelProperty("用户手机")
private String mobile;
🔐 权限控制集成
RuoYi框架与Shiro权限系统完美集成,Swagger页面访问需要相应权限:
@Controller
@RequestMapping("/tool/swagger")
public class SwaggerController extends BaseController {
@RequiresPermissions("tool:swagger:view")
@GetMapping()
public String index() {
return redirect("/swagger-ui/index.html");
}
}
权限配置表
| 权限标识 | 权限描述 | 默认角色 |
|---|---|---|
| tool:swagger:view | 查看Swagger文档 | 管理员 |
| tool:swagger:edit | 编辑API文档 | 开发人员 |
🛠️ 完整示例代码
用户管理API示例
@Api(tags = "用户信息管理")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController {
private final static Map<Integer, UserEntity> users = new LinkedHashMap<>();
{
users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
}
@ApiOperation("获取用户列表")
@GetMapping("/list")
public R<List<UserEntity>> userList() {
List<UserEntity> userList = new ArrayList<>(users.values());
return R.ok(userList);
}
@ApiOperation("获取用户详细")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path")
@GetMapping("/{userId}")
public R<UserEntity> getUser(@PathVariable Integer userId) {
if (!users.isEmpty() && users.containsKey(userId)) {
return R.ok(users.get(userId));
} else {
return R.fail("用户不存在");
}
}
@ApiOperation("新增用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer"),
@ApiImplicitParam(name = "username", value = "用户名称", dataType = "String"),
@ApiImplicitParam(name = "password", value = "用户密码", dataType = "String"),
@ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String")
})
@PostMapping("/save")
public R<String> save(UserEntity user) {
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
return R.fail("用户ID不能为空");
}
users.put(user.getUserId(), user);
return R.ok();
}
}
@ApiModel(value = "UserEntity", description = "用户实体")
class UserEntity {
@ApiModelProperty("用户ID")
private Integer userId;
@ApiModelProperty("用户名称")
private String username;
@ApiModelProperty("用户密码")
private String password;
@ApiModelProperty("用户手机")
private String mobile;
// 构造方法、getter、setter省略
}
🌐 访问与使用
Swagger UI访问地址
| 环境 | 访问地址 | 说明 |
|---|---|---|
| 本地开发 | http://localhost:80/swagger-ui/index.html | 默认端口80 |
| 测试环境 | http://your-domain.com/swagger-ui/index.html | 根据实际部署 |
| 生产环境 | 建议关闭或使用权限控制 | 安全考虑 |
接口测试流程
sequenceDiagram
participant 开发者
participant Swagger UI
participant 后端API
participant 数据库
开发者->>Swagger UI: 1. 打开文档页面
Swagger UI->>后端API: 2. 加载API定义
后端API-->>Swagger UI: 3. 返回API信息
Swagger UI->>开发者: 4. 显示交互界面
开发者->>Swagger UI: 5. 选择接口并填写参数
Swagger UI->>后端API: 6. 发送API请求
后端API->>数据库: 7. 执行数据操作
数据库-->>后端API: 8. 返回操作结果
后端API-->>Swagger UI: 9. 返回响应数据
Swagger UI->>开发者: 10. 显示响应结果
🔧 高级配置技巧
1. 自定义API分组
@Bean
public Docket createUserApi() {
return new Docket(DocumentationType.OAS_30)
.groupName("用户管理")
.select()
.apis(RequestHandlerSelectors.basePackage("com.ruoyi.web.controller.system"))
.paths(PathSelectors.ant("/system/user/**"))
.build();
}
@Bean
public Docket createToolApi() {
return new Docket(DocumentationType.OAS_30)
.groupName("工具接口")
.select()
.apis(RequestHandlerSelectors.basePackage("com.ruoyi.web.controller.tool"))
.paths(PathSelectors.ant("/tool/**"))
.build();
}
2. 响应模型定制
@ApiResponses({
@ApiResponse(code = 200, message = "操作成功", response = R.class),
@ApiResponse(code = 500, message = "系统异常", response = R.class)
})
@PostMapping("/update")
public R<String> update(@RequestBody UserEntity user) {
// 业务逻辑
}
3. 枚举类型支持
@ApiModelProperty(value = "用户状态", allowableValues = "NORMAL, DISABLED, LOCKED")
private UserStatus status;
public enum UserStatus {
@ApiModelProperty("正常")
NORMAL,
@ApiModelProperty("禁用")
DISABLED,
@ApiModelProperty("锁定")
LOCKED
}
🚨 生产环境部署建议
安全配置策略
# 生产环境配置
swagger:
enabled: false # 关闭Swagger
# 或者通过环境变量控制
spring:
profiles:
active: prod
@Profile({"dev", "test"}) // 仅在开发和测试环境启用
@Configuration
public class SwaggerConfig {
// 配置内容
}
访问控制配置
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.enable(isSwaggerEnabled()) // 动态判断
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private List<SecurityScheme> securitySchemes() {
return Collections.singletonList(
new ApiKey("Authorization", "Authorization", "header"));
}
private List<SecurityContext> securityContexts() {
return Collections.singletonList(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.any())
.build());
}
📊 性能优化建议
1. 减少不必要的注解扫描
.select()
// 精确指定包路径,避免全包扫描
.apis(RequestHandlerSelectors.basePackage("com.ruoyi.web.controller"))
// 或者使用注解过滤
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.build();
2. 启用缓存配置
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
.resourceChain(false);
}
};
}
🔍 常见问题排查
问题1:Swagger页面无法访问
症状: 404错误或空白页面 解决方案:
- 检查
swagger.enabled配置是否为true - 确认依赖包是否正确引入
- 检查是否有权限拦截器阻止访问
问题2:注解不生效
症状: 注解添加后文档无变化 解决方案:
- 确认使用了正确的注解导入
io.swagger.annotations.* - 检查API扫描路径配置
- 清理项目重新编译
问题3:类型转换错误
症状: 页面显示类型转换异常 解决方案:
<!-- 添加特定版本的swagger-models -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.2</version>
</dependency>
📈 最佳实践总结
注解使用规范表
| 注解类型 | 使用场景 | 必填项 | 示例 |
|---|---|---|---|
| @Api | 控制器类 | tags | @Api(tags = "用户管理") |
| @ApiOperation | 接口方法 | value | @ApiOperation("获取用户") |
| @ApiImplicitParam | 方法参数 | name, value | @ApiImplicitParam(name="id", value="ID") |
| @ApiModel | 实体类 | value | @ApiModel(value="User") |
| @ApiModelProperty | 实体字段 | value | @ApiModelProperty("用户名") |
版本控制策略
@ApiOperation(value = "创建用户", notes = "v2.0版本新增字段验证")
@PostMapping("/v2/users")
public R<User> createUserV2(@RequestBody User user) {
// 新版本逻辑
}
🎯 总结与展望
RuoYi框架的Swagger集成提供了完整的API文档自动化解决方案。通过合理的配置和规范的注解使用,可以显著提升开发效率和文档质量。
关键优势:
- ✅ 零配置开箱即用
- ✅ 与权限系统完美集成
- ✅ 支持丰富的注解定制
- ✅ 生产环境安全可控
- ✅ 良好的性能表现
随着OpenAPI规范的不断发展,建议关注Swagger到SpringDoc的迁移路径,以获得更好的性能和更丰富的功能支持。
下一步学习建议:
- 深入掌握OpenAPI 3.0规范细节
- 学习API-first开发模式
- 探索API网关与文档集成
- 了解自动化测试与文档的联动
通过本文的详细解析,相信你已经掌握了RuoYi中Swagger集成的精髓。开始实践吧,让API文档成为你开发过程中的得力助手!
登录后查看全文
热门项目推荐
相关项目推荐
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0153- DDeepSeek-V4-ProDeepSeek-V4-Pro(总参数 1.6 万亿,激活 49B)面向复杂推理和高级编程任务,在代码竞赛、数学推理、Agent 工作流等场景表现优异,性能接近国际前沿闭源模型。Python00
LongCat-Video-Avatar-1.5最新开源LongCat-Video-Avatar 1.5 版本,这是一款经过升级的开源框架,专注于音频驱动人物视频生成的极致实证优化与生产级就绪能力。该版本在 LongCat-Video 基础模型之上构建,可生成高度稳定的商用级虚拟人视频,支持音频-文本转视频(AT2V)、音频-文本-图像转视频(ATI2V)以及视频续播等原生任务,并能无缝兼容单流与多流音频输入。00
auto-devAutoDev 是一个 AI 驱动的辅助编程插件。AutoDev 支持一键生成测试、代码、提交信息等,还能够与您的需求管理系统(例如Jira、Trello、Github Issue 等)直接对接。 在IDE 中,您只需简单点击,AutoDev 会根据您的需求自动为您生成代码。Kotlin03
Intern-S2-PreviewIntern-S2-Preview,这是一款高效的350亿参数科学多模态基础模型。除了常规的参数与数据规模扩展外,Intern-S2-Preview探索了任务扩展:通过提升科学任务的难度、多样性与覆盖范围,进一步释放模型能力。Python00
skillhubopenJiuwen 生态的 Skill 托管与分发开源方案,支持自建与可选 ClawHub 兼容。Python0112
项目优选
收起
暂无描述
Dockerfile
733
4.75 K
deepin linux kernel
C
31
16
Ascend Extension for PyTorch
Python
652
797
Claude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed.
Get Started
Rust
1.25 K
153
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
1.1 K
611
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.01 K
1.01 K
华为昇腾面向大规模分布式训练的多模态大模型套件,支撑多模态生成、多模态理解。
Python
147
237
昇腾LLM分布式训练框架
Python
168
200
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
434
395
暂无简介
Dart
986
253