Swagger 配置指南——快速构建 API 文档

在现代 Web 开发中,API 文档是前后端协作的重要桥梁。Swagger 是一个强大的工具,可以帮助我们自动生成 API 文档,并提供交互式的 API 测试界面。本文将详细介绍如何在 Spring Boot 项目中配置 Swagger,并生成美观且实用的 API 文档。


1. Swagger 简介

Swagger 是一套围绕 OpenAPI 规范构建的工具,用于设计、构建、记录和使用 RESTful API。通过 Swagger,开发者可以:

  • 自动生成 API 文档。
  • 提供交互式的 API 测试界面。
  • 支持多种语言和框架(如 Java、Python、Node.js 等)。

2. Spring Boot 集成 Swagger

2.1 添加依赖

首先,在 pom.xml 中添加 Swagger 的依赖:

xml 复制代码
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>
  • springfox-swagger2:核心库,用于生成 API 文档。
  • springfox-swagger-ui:提供交互式的 API 测试界面。

2.2 配置 Swagger

在 Spring Boot 项目中,创建一个配置类来启用 Swagger:

java 复制代码
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("API 文档")
                        .description("Spring Boot 集成 Swagger 示例")
                        .version("1.0")
                        .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 指定扫描的包
                .paths(PathSelectors.any())
                .build();
    }
}
  • @EnableSwagger2:启用 Swagger。
  • Docket:配置 Swagger 的核心 Bean。
  • apiInfo:设置 API 文档的基本信息,如标题、描述、版本等。
  • apis:指定扫描的控制器包路径。
  • paths:指定需要生成文档的 API 路径。

2.3 启动项目并访问 Swagger UI

启动 Spring Boot 项目后,访问以下 URL 即可查看 Swagger UI:

bash 复制代码
http://localhost:8080/swagger-ui.html
  • Swagger UI:提供交互式的 API 测试界面,支持在线测试 API。

3. Swagger 注解详解

Swagger 提供了一系列注解,用于增强 API 文档的可读性和实用性。

3.1 @Api
  • 作用:标注在控制器类上,用于描述整个控制器。

  • 示例

    java 复制代码
    @Api(tags = "用户管理")
    @RestController
    @RequestMapping("/user")
    public class UserController {
        // ...
    }
3.2 @ApiOperation
  • 作用:标注在方法上,用于描述 API 的功能。

  • 示例

    java 复制代码
    @ApiOperation(value = "获取用户信息", notes = "根据用户 ID 获取用户信息")
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // ...
    }
3.3 @ApiParam
  • 作用:标注在方法参数上,用于描述参数的含义。

  • 示例

    java 复制代码
    @ApiOperation(value = "更新用户信息")
    @PutMapping("/{id}")
    public void updateUser(
            @ApiParam(value = "用户 ID", required = true) @PathVariable Long id,
            @ApiParam(value = "用户信息", required = true) @RequestBody User user) {
        // ...
    }
3.4 @ApiModel@ApiModelProperty
  • 作用:标注在实体类上,用于描述模型及其属性。

  • 示例

    java 复制代码
    @ApiModel(description = "用户实体")
    public class User {
        @ApiModelProperty(value = "用户 ID")
        private Long id;
    
        @ApiModelProperty(value = "用户名", required = true)
        private String username;
    
        // getters and setters
    }

4. Swagger 高级配置

4.1 分组配置

如果项目中有多个模块,可以为每个模块配置不同的 Swagger 分组:

java 复制代码
@Bean
public Docket userApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .groupName("用户管理")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo.user"))
            .paths(PathSelectors.any())
            .build();
}

@Bean
public Docket orderApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .groupName("订单管理")
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo.order"))
            .paths(PathSelectors.any())
            .build();
}
4.2 全局参数配置

如果需要为所有 API 添加全局参数(如 Token),可以配置如下:

java 复制代码
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .globalOperationParameters(Collections.singletonList(
                    new ParameterBuilder()
                            .name("Authorization")
                            .description("访问令牌")
                            .modelRef(new ModelRef("string"))
                            .parameterType("header")
                            .required(false)
                            .build()
            ))
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
            .paths(PathSelectors.any())
            .build();
}

5. 总结

通过 Swagger,我们可以快速生成美观且实用的 API 文档,并支持在线测试 API。本文详细介绍了如何在 Spring Boot 项目中配置 Swagger,并讲解了常用的 Swagger 注解和高级配置。希望本文能帮助你更好地使用 Swagger,提升开发效率!

相关推荐
只在空想家6 分钟前
Servlet 体系结构
java·后端·servlet
ApiHug7 分钟前
ApiHug 1.3.9 支持 Spring 3.5.0 + Plugin 0.7.4 内置小插件升级!儿童节快乐!!!
java·后端·spring·api·apihug·apismart
玛奇玛丶9 分钟前
💥昨天掘金 Web 端突然登不上了,一次网络异常的排查记录
后端·负载均衡
南囝coding13 分钟前
这款AI自动生成播客工具,必须收藏!
前端·后端
追逐时光者18 分钟前
C#/.NET/.NET Core优秀项目和框架2025年5月简报
后端·.net
37手游后端团队1 小时前
8分钟带你看懂什么是MCP
人工智能·后端·面试
小华同学ai2 小时前
千万别错过!这个国产开源项目彻底改变了你的域名资产管理方式,收藏它相当于多一个安全专家!
前端·后端·github
Vowwwwwww2 小时前
GIT历史存在大文件的解决办法
前端·git·后端
捡田螺的小男孩2 小时前
京东一面:接口性能优化,有哪些经验和手段
java·后端·面试
艾露z2 小时前
深度解析Mysql中MVCC的工作机制
java·数据库·后端·mysql