快速理解

Swagger 可以定义标准的RESTful风格的API,API规范。
Swagger官网
Swagger GitHub地址
菜鸟教程

Swagger 的核心组件包括:

  • Swagger UI:一个可视化界面,用于交互式地查看和测试 API。
  • Swagger Editor:一个在线编辑器,支持实时预览 API 文档。
  • Swagger Codegen:一个代码生成工具,可以根据 API 定义自动生成客户端或服务端代码。
  • Swagger Hub:一个集成的 API 设计和文档平台,提供协作功能和云存储。

Swagger 的核心功能:

  1. 开发 API 支持两种开发模式:
    1. 代码优先:从已有代码生成 OpenAPI 文档。
    2. 设计优先:通过 Swagger Editor 先设计 API,再通过 Swagger Codegen 生成代码。
  2. 交互 API 文档
    Swagger UI,支持通过浏览器直接与 API 交互、发送请求、查看响应,极大地方便了开发者和测试人员。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
openapi: 3.0.0
info:
title: Sample API
description: API description
version: 1.0.0
servers:
- url: https://api.example.com/v1
paths:
/users:
get:
summary: Returns a list of users
responses:
'200':
description: A JSON array of user names
content:
application/json:
schema:
type: array
items:
type: string

OpenAPI 规范的结构

OpenAPI 文档通常以 YAML 或 JSON 格式编写。
下面是一个基本的 OpenAPI 文档结构:

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 文档元数据 (info)
openapi: 3.1.0 # OpenAPI 版本
info:
title: 示例 API # API 名称
description: 这是一个示例 API 文档
version: 1.0.0 # API 版本
# 服务器信息 (servers)
servers:
- url: https://api.example.com/v1 # API 服务器地址
description: 生产环境
- url: https://dev-api.example.com/v1
description: 开发环境
# 路径 (paths) 操作 (operations)
paths: # API 路径定义
/users: # 端点路径
get: # HTTP 方法
summary: 获取所有用户
description: 返回系统中的所有用户列表
operationId: getUsers
tags:
- users # 分组标签
# 参数 (parameters) 请求体 (requestBody)
parameters: # 请求参数
- name: limit
in: query
description: 返回结果数量限制
schema:
type: integer
default: 20
# 响应 (responses)
responses: # 响应定义
'200': # HTTP 状态码
description: 成功返回用户列表
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/User'
'400':
description: 错误的请求参数
# 组件 (components)
components: # 可复用组件
# 数据模型 (schemas)
schemas: # 数据模型定义
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
email:
type: string
format: email
required:
- id
- name
# 安全 (security)

Springfox (2020年3.0.0 版本之后再无更新被SpringDoc代替)

Springfox 开源API Doc的框架,前身是swagger-springmvc
可以将 Controller 中的方法以文档的形式展现。
官方定义为: Automated JSON API documentation for API’s built with Spring。

Swagger 的使用

引入依赖

1
2
3
4
5
6
7
8
9
10
11
<!-- swagger 接口文档 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

新建config/Swagger配置类

警告
线上环境不要把接口暴露出去!!! 可以通过在 SwaggerConfig 配置文件开头加上 @Profile({"dev", "test"}) 限定配置仅在部分环境开启

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
41
42
/**
* @author wgzc
* @date 2025/11/25
* 自定义 Swagger 接口文档的配置
*/
@Configuration // 配置类
@EnableSwagger2 // 开启 swagger2 的自动配置
public class SwaggerConfig {
@Bean
public Docket docket() {
// 创建一个 swagger 的 bean 实例
return new Docket(DocumentationType.SWAGGER_2)
// 配置接口信息
.select() // 设置扫描接口
// 配置如何扫描接口
.apis(RequestHandlerSelectors
//.any() // 扫描全部的接口,默认
//.none() // 全部不扫描
.basePackage("com.yupi.usercenter.controller") // 扫描指定包下的接口,最为常用
//.withClassAnnotation(RestController.class) // 扫描带有指定注解的类下所有接口
//.withMethodAnnotation(PostMapping.class) // 扫描带有只当注解的方法接口

).paths(PathSelectors.any() // 满足条件的路径,该断言总为true
//.none() // 不满足条件的路径,该断言总为false(可用于生成环境屏蔽 swagger)
//.ant("/user/**") // 满足字符串表达式路径
//.regex("") // 符合正则的路径
).build();
}

// 基本信息设置
private ApiInfo apiInfo() {
Contact contact = new Contact("wgzc", // 作者姓名
"https://wzcwzc10.github.io/", // 作者网址
"3412399241@qq.com"); // 作者邮箱
return new ApiInfoBuilder().title("泡泡伙伴匹配系统-接口文档") // 标题
.description("你若盛开,清风徐来") // 描述
.termsOfServiceUrl("https://github.com/wzcwzc10") // 跳转连接
.version("1.0") // 版本
.license("Swagger-的使用(详细教程)").licenseUrl("https://github.com/wzcwzc10").contact(contact).build();
}
}

SpringBoot 版本 >= 2.6 大概率会报错:
Failed to start bean 'documentationPluginsBootstrapper';
在 application.yaml 中添加配置:

1
2
3
4
5
spring:
# ......
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER

运行此地址URLhttp://localhost:8080/api/swagger-ui.html