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文档成为你开发过程中的得力助手!
登录后查看全文
热门项目推荐
相关项目推荐
GLM-5智谱 AI 正式发布 GLM-5,旨在应对复杂系统工程和长时域智能体任务。Jinja00
GLM-5-w4a8GLM-5-w4a8基于混合专家架构,专为复杂系统工程与长周期智能体任务设计。支持单/多节点部署,适配Atlas 800T A3,采用w4a8量化技术,结合vLLM推理优化,高效平衡性能与精度,助力智能应用开发Jinja00
请把这个活动推给顶尖程序员😎本次活动专为懂行的顶尖程序员量身打造,聚焦AtomGit首发开源模型的实际应用与深度测评,拒绝大众化浅层体验,邀请具备扎实技术功底、开源经验或模型测评能力的顶尖开发者,深度参与模型体验、性能测评,通过发布技术帖子、提交测评报告、上传实践项目成果等形式,挖掘模型核心价值,共建AtomGit开源模型生态,彰显顶尖程序员的技术洞察力与实践能力。00
Kimi-K2.5Kimi K2.5 是一款开源的原生多模态智能体模型,它在 Kimi-K2-Base 的基础上,通过对约 15 万亿混合视觉和文本 tokens 进行持续预训练构建而成。该模型将视觉与语言理解、高级智能体能力、即时模式与思考模式,以及对话式与智能体范式无缝融合。Python00
MiniMax-M2.5MiniMax-M2.5开源模型,经数十万复杂环境强化训练,在代码生成、工具调用、办公自动化等经济价值任务中表现卓越。SWE-Bench Verified得分80.2%,Multi-SWE-Bench达51.3%,BrowseComp获76.3%。推理速度比M2.1快37%,与Claude Opus 4.6相当,每小时仅需0.3-1美元,成本仅为同类模型1/10-1/20,为智能应用开发提供高效经济选择。【此简介由AI生成】Python00
Qwen3.5Qwen3.5 昇腾 vLLM 部署教程。Qwen3.5 是 Qwen 系列最新的旗舰多模态模型,采用 MoE(混合专家)架构,在保持强大模型能力的同时显著降低了推理成本。00- RRing-2.5-1TRing-2.5-1T:全球首个基于混合线性注意力架构的开源万亿参数思考模型。Python00
项目优选
收起
deepin linux kernel
C
27
11
OpenHarmony documentation | OpenHarmony开发者文档
Dockerfile
567
3.83 K
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
892
667
Ascend Extension for PyTorch
Python
376
446
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
349
200
昇腾LLM分布式训练框架
Python
116
145
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
1.37 K
778
暂无简介
Dart
798
197
React Native鸿蒙化仓库
JavaScript
308
359
openJiuwen agent-studio提供零码、低码可视化开发和工作流编排,模型、知识库、插件等各资源管理能力
TSX
1.13 K
271