0%

Swagger介绍

Swagger 详解:前后端接口文档的自动化解决方案

在前后端分离的开发模式中,接口文档是连接前端与后端的关键桥梁。Swagger(现更名为 OpenAPI)作为一款强大的 API 文档生成工具,不仅能自动生成交互式接口文档,还支持在线接口调试,极大提升了开发效率。本文基于提供的配置示例,详细介绍 Swagger 的核心功能、配置方式及常用注解。

Swagger 核心价值与依赖引入

核心优势

  • 自动化文档生成:通过代码注解自动生成 API 文档,避免手动编写文档的繁琐与不一致;
  • 交互式调试:提供 Web 界面可直接调用接口,支持参数填写、响应查看,替代 Postman 等工具的部分功能;
  • 版本管理:随代码迭代自动更新文档,保持文档与代码的一致性;
  • 跨语言支持:支持多种编程语言(Java、Python 等),是前后端协作的通用标准。

依赖引入(Spring Boot 项目)

pom.xml中添加 Swagger2 的依赖(以 2.8.0 版本为例):

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
  • springfox-swagger2:核心依赖,提供 Swagger 的注解解析与文档生成功能;
  • springfox-swagger-ui:提供 Web 界面,用于展示和调试接口(访问地址:http://项目地址:端口/swagger-ui.html)。

Swagger 核心配置

通过 Java 配置类开启 Swagger 并自定义文档信息,核心是创建Docket对象(Swagger 的主要配置入口)。

完整配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration // 标识为配置类
@EnableSwagger2 // 开启Swagger2功能
public class SwaggerConfig {

/**
* 创建Docket对象,配置Swagger核心参数
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2) // 指定API类型为SWAGGER_2
.apiInfo(apiInfo()) // 设置API文档信息
.select() // 开始配置扫描范围
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) // 扫描指定包下的接口
.paths(PathSelectors.regex("/user.*")) // 过滤路径(只包含/user开头的接口)
.groupName("用户管理模块") // 接口分组(多模块项目常用)
.build();
}

/**
* 定义API文档的基本信息(展示在文档首页)
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户管理系统API文档") // 文档标题
.description("用于用户注册、查询、修改的接口文档") // 文档描述
.termsOfServiceUrl("http://localhost:8080/") // 服务条款地址(可选)
.version("1.0.0") // 文档版本
.build();
}
}

配置参数解析

  1. Docket核心方法
    • DocumentationType.SWAGGER_2:指定 Swagger 版本(目前主流为 2.x);
    • apiInfo():关联 API 文档的基本信息(标题、描述等);
    • select():开启接口扫描配置;
    • apis():指定需要扫描的接口范围:
      • RequestHandlerSelectors.basePackage("包路径"):扫描指定包下的 Controller;
      • RequestHandlerSelectors.withClassAnnotation(Api.class):扫描带有@Api注解的类;
    • paths():过滤接口路径(如PathSelectors.any()匹配所有路径,PathSelectors.none()排除所有路径);
    • groupName():多模块项目中用于分组接口(如 “用户模块”“订单模块”)。
  2. ApiInfo参数
    • title:文档标题(将显示在 Swagger UI 首页);
    • description:文档详细描述;
    • version:接口版本号(与项目版本同步);
    • 其他可选参数:contact()(作者信息)、license()(许可证信息)等。

常用 Swagger 注解详解

Swagger 通过注解为接口添加元数据(如说明、参数含义等),生成的文档更清晰易懂。注解分为接口层面(Controller 与方法)和数据模型层面(DTO/POJO)两类。

1. 接口层面注解

(1)@Api:标注在 Controller 类上,描述类的功能
1
2
3
4
5
6
7
8
9
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "用户管理接口", description = "负责用户的注册、查询、修改等操作")
@RestController
@RequestMapping("/user")
public class UserController {
// ...
}
  • tags:给接口分组(UI 中会按 tags 归类展示);
  • description:对 Controller 的详细描述(可选)。
(2)@ApiOperation:标注在方法上,描述接口的功能
1
2
3
4
5
6
7
8
9
10
11
12
13
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@ApiOperation(
value = "根据ID查询用户",
notes = "精确查询单个用户信息,支持模糊查询姓名",
tags = "查询接口" // 可覆盖类的tags分组
)
@GetMapping("/{id}")
public UserVO getUserById(@PathVariable Long id) {
// ...
}
  • value:接口的简短说明(显示在接口列表中);
  • notes:接口的详细备注(显示在接口详情页);
  • tags:用于给方法单独分组(优先级高于类的@Api.tags)。
(3)@ApiParam:标注在方法参数上,描述参数信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@PostMapping("/login")
public Result login(
@ApiParam(name = "username", value = "用户名", required = true, example = "zhangsan")
@RequestParam String username,

@ApiParam(name = "password", value = "密码", required = true, example = "123456")
@RequestParam String password
) {
// ...
}
  • name:参数名称(与方法参数名一致);
  • value:参数的中文说明;
  • required:是否为必填参数(Swagger UI 会标红提示);
  • example:参数的示例值(在 UI 中默认显示)。
(4)@ApiImplicitParams@ApiImplicitParam:描述多个参数(替代@ApiParam,适合参数较多的场景)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.web.bind.annotation.PutMapping;

@PutMapping("/update")
@ApiImplicitParams({
@ApiImplicitParam(
name = "id",
value = "用户ID",
required = true,
paramType = "query", // 参数位置(query/path/header/body/form)
dataType = "Long" // 参数类型
),
@ApiImplicitParam(
name = "name",
value = "用户姓名",
required = false,
paramType = "query",
dataType = "String",
example = "李四"
)
})
public Result updateUser(Long id, String name) {
// ...
}
  • paramType:参数所在位置:
    • query:对应@RequestParam(URL 查询参数);
    • path:对应@PathVariable(URL 路径参数);
    • header:对应@RequestHeader(请求头参数);
    • body:对应@RequestBody(请求体参数,通常为 JSON);
  • dataType:参数的数据类型(如StringInteger)。
(5)@ApiResponses@ApiResponse:描述接口的响应状态
1
2
3
4
5
6
7
8
9
10
11
12
13
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.DeleteMapping;

@DeleteMapping("/{id}")
@ApiResponses({
@ApiResponse(code = 200, message = "删除成功"),
@ApiResponse(code = 404, message = "用户不存在"),
@ApiResponse(code = 500, message = "服务器内部错误")
})
public Result deleteUser(@PathVariable Long id) {
// ...
}
  • code:HTTP 响应状态码(如 200、404、500);
  • message:响应状态的说明(在 UI 中展示为 “响应消息”)。
(6)@ApiIgnore:忽略某个接口或参数(不生成文档)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import io.swagger.annotations.ApiIgnore;
import org.springframework.web.bind.annotation.GetMapping;

// 忽略整个方法
@ApiIgnore
@GetMapping("/internal/log")
public Result getInternalLog() {
// ...
}

// 忽略某个参数
public Result query(
@RequestParam String key,
@ApiIgnore @RequestParam(required = false) String token // 内部参数,不对外暴露
) {
// ...
}

2. 数据模型层面注解(DTO/POJO)

用于描述请求体(@RequestBody)或响应体中使用的 Java 对象,使文档能展示对象的属性信息。

(1)@ApiModel:标注在类上,描述数据模型的作用
1
2
3
4
5
6
7
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel(value = "UserDTO", description = "用户注册请求参数")
public class UserDTO {
// ...
}
  • value:模型名称;
  • description:模型的详细描述。
(2)@ApiModelProperty:标注在属性上,描述字段信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class UserDTO {
@ApiModelProperty(
name = "id",
value = "用户ID(注册时无需传递,由系统生成)",
hidden = true // 隐藏该字段(不在文档中显示)
)
private Long id;

@ApiModelProperty(
value = "用户名",
required = true,
example = "zhangsan",
allowableValues = "length[3,20]" // 允许的值范围(可选)
)
private String username;

@ApiModelProperty(
value = "用户年龄",
required = false,
dataType = "Integer",
example = "20"
)
private Integer age;
}
  • required:是否为必填字段;
  • example:字段的示例值(在 UI 的 “请求示例” 中显示);
  • hidden:是否隐藏字段(如敏感字段password可设置为hidden = true);
  • allowableValues:字段的允许值范围(如"0,1,2"表示枚举值,"range[1,100]"表示数值范围)。

Swagger UI 使用指南

配置完成后,启动项目并访问http://localhost:8080/swagger-ui.html(端口与项目一致),即可看到生成的接口文档界面,主要功能包括:

  1. 接口分组查看:按groupNametags分组展示接口,支持搜索;
  2. 接口详情查看:点击接口名称可展开详情,包括参数说明、响应状态、请求示例等;
  3. 在线调试:点击 “Try it out” 按钮,填写参数后点击 “Execute” 即可发送请求,查看响应结果;
  4. 文档导出:支持导出 JSON 或 YAML 格式的 API 文档(通过页面顶部的 “Download” 按钮)。

注意事项与最佳实践

  1. 生产环境关闭 Swagger
    Swagger 文档包含接口细节,生产环境应禁用,可通过@Profile({"dev", "test"})注解限制仅在开发 / 测试环境生效:

    1
    2
    3
    4
    @Configuration
    @EnableSwagger2
    @Profile({"dev", "test"}) // 仅在dev和test环境启用
    public class SwaggerConfig { ... }
  2. 参数说明要清晰
    避免使用模糊的描述(如 “参数 1”“数据”),应明确说明参数的含义、格式(如日期格式yyyy-MM-dd)、取值范围等。

  3. 合理分组接口
    多模块项目通过groupNametags分组,便于前端开发者快速定位所需接口。

  4. 版本兼容问题
    不同版本的 Swagger 依赖可能存在冲突,建议使用稳定版本(如 2.9.2),并注意与 Spring Boot 版本的兼容性(Spring Boot 2.x 推荐使用 Swagger 2.9.x 及以上)。

总结

Swagger 通过自动化文档生成和交互式调试,解决了传统接口文档维护困难、沟通成本高的问题,是前后端分离开发中的必备工具。掌握其核心配置(DocketApiInfo)和常用注解(@Api@ApiOperation@ApiModel等),能生成清晰、规范的接口文档,显著提升团队协作效率

欢迎关注我的其它发布渠道

表情 | 预览
快来做第一个评论的人吧~
Powered By Valine
v1.3.10