若依框架整合Swagger生成接口文档

2025-06发布2次浏览

若依框架(RuoYi)是一个基于Spring Boot和Spring Cloud的快速开发平台,提供了许多开箱即用的功能模块。Swagger则是一个强大的API文档生成工具,可以自动生成RESTful API文档,并提供在线测试功能。将Swagger整合到若依框架中,不仅可以提高开发效率,还能让接口文档更加规范、易于维护。

接下来,我们将详细介绍如何在若依框架中整合Swagger生成接口文档。


1. 环境准备

在开始整合之前,请确保以下环境已经配置完成:

  • JDK 8 或更高版本
  • Maven 构建工具
  • 若依框架已成功运行

2. 引入Swagger依赖

在若依项目的pom.xml文件中添加Swagger相关依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

注意:如果使用的是Spring Boot 3.x版本,需要引入与之兼容的Swagger版本。


3. 配置Swagger

创建一个Swagger配置类,用于定义API文档的基本信息和分组规则。

示例代码:

package com.ruoyi.common.swagger;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.ruoyi")) // 指定扫描的包路径
                .paths(PathSelectors.any()) // 指定路径规则
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("若依框架API文档") // 文档标题
                .description("若依框架整合Swagger生成的API文档") // 文档描述
                .version("1.0") // 版本号
                .build();
    }
}

4. 启用Swagger UI

application.ymlapplication.properties中添加以下配置以启用Swagger UI:

application.yml示例:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher # 兼容Swagger的路径匹配策略

swagger:
  enabled: true # 开启Swagger

5. 测试Swagger功能

启动项目后,访问以下地址即可查看生成的API文档:

http://localhost:8080/swagger-ui/index.html

页面加载完成后,您可以看到所有被扫描到的接口及其详细信息,包括请求方法、参数、响应等。


6. 自定义扩展

6.1 接口分组

如果项目中有多个模块,可以通过分组来区分不同的API文档。

示例代码:
@Bean
public Docket userApi() {
    return new Docket(DocumentationType.OAS_30)
            .groupName("用户管理") // 分组名称
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.ruoyi.system.controller"))
            .paths(PathSelectors.ant("/user/**")) // 限定路径
            .build();
}

@Bean
public Docket orderApi() {
    return new Docket(DocumentationType.OAS_30)
            .groupName("订单管理")
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.ruoyi.business.controller"))
            .paths(PathSelectors.ant("/order/**"))
            .build();
}

6.2 添加全局参数

可以在Swagger中为所有接口添加全局参数,例如Token认证信息。

示例代码:
private List<Parameter> getGlobalParameters() {
    Parameter token = new ParameterBuilder()
            .name("Authorization") // 参数名
            .description("用户Token") // 参数描述
            .modelRef(new ModelRef("string"))
            .parameterType("header") // 参数类型
            .required(false) // 是否必填
            .build();
    return Collections.singletonList(token);
}

@Bean
public Docket createRestApiWithGlobalParams() {
    return new Docket(DocumentationType.OAS_30)
            .globalOperationParameters(getGlobalParameters())
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.ruoyi"))
            .paths(PathSelectors.any())
            .build();
}

7. 注意事项

  1. 生产环境关闭Swagger:为了安全考虑,在生产环境中应关闭Swagger功能。可以通过设置swagger.enabled=false来实现。
  2. 接口注解优化:为接口添加详细的注解,如@ApiOperation@ApiParam等,可以让生成的文档更加清晰。
    • @ApiOperation:描述接口功能。
    • @ApiParam:描述接口参数。
示例代码:
@ApiOperation(value = "获取用户信息", notes = "根据用户ID查询用户详细信息")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long", paramType = "query")
@GetMapping("/getUser")
public User getUser(@RequestParam Long userId) {
    return userService.getUserById(userId);
}

8. 总结

通过以上步骤,我们成功地在若依框架中整合了Swagger,实现了API文档的自动化生成和维护。这种整合不仅提高了开发效率,还为团队协作提供了便利。