一、什么是 Swagger?
Swagger 是一套用于设计、构建、文档化和测试 RESTful API的开源工具
主要组件:
- Swagger UI:可视化展示API文档的网页界面。
- Swagger Editor:在线编辑API的工具。
- Swagger Codegen:自动生成客户端SDK、服务端代码或文档。
- Springfox/Swagger-Springdoc:Spring Boot中常用的Swagger集成工具。
二、为什么使用 Swagger?
| 作用 | 说明 |
|---|---|
| 自动生成文档 | 减少手写文档,随代码自动更新 |
| 支持接口测试 | 可直接在网页上测试API接口 |
| 前后端协作 | 前后端基于统一规范沟通接口 |
| 代码生成 | 支持生成SDK或服务端框架代码 |
三、如何使用 Swagger
引入依赖
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.7.0</version>
</dependency>
在配置类中配置Swagger
@Configuration
public class SwaggerConfig {
@Bean
public GroupedOpenApi api() {
return GroupedOpenApi.builder()
.group("test接口")
.packagesToScan("com.example.demo.controller") // 扫描 controller 包
.build();
}
}
编写接口注释
@RestController
@RequestMapping("/user")
public class UserController {
@Operation(summary = "获取用户信息", description = "根据用户ID获取详细信息")
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "java");
}
}
访问 Swagger UI
项目启动后访问默认地址:
http://localhost:8080/swagger-ui/index.html
四、常用注解
| 注解 | 说明 |
|---|---|
@OpenAPIDefinition |
配置 API 的元信息 |
@Operation |
描述单个接口的方法(title, description 等) |
@Parameter |
描述请求参数 |
@Schema |
描述模型属性 |
@ApiResponse |
描述接口响应 |
Swagger 常用注解与属性详解
1. @Operation
用于描述接口信息
@Operation(
summary = "简要描述接口作用",
description = "详细的接口说明",
operationId = "唯一标识名",
tags = {"用户模块"}
)
| 属性 | 含义 |
|---|---|
summary |
接口的简要描述 |
description |
接口详细说明 |
operationId |
接口唯一标识(不能重复) |
tags |
所属分组,用于分模块展示 |
2. @Parameter
用于描述单个参数
@Parameter(
name = "id",
description = "用户ID",
required = true,
in = ParameterIn.PATH,
schema = @Schema(type = "integer", format = "int64")
)
| 属性 | 含义 |
|---|---|
name |
参数名称(与方法参数名匹配) |
description |
参数说明 |
required |
是否必填 |
in |
参数位置:PATH、QUERY、HEADER等 |
schema |
数据类型描述(使用 @Schema) |
3. @Schema
用于描述实体字段或参数类型
@Schema(
description = "用户名",
example = "Tom",
required = true,
type = "string"
)
private String username;
| 属性 | 含义 |
|---|---|
description |
字段说明 |
example |
示例值 |
required |
是否必填 |
type |
数据类型 |
4. @ApiResponse
用于描述返回信息
@ApiResponse(
responseCode = "200",
description = "请求成功",
content = @Content(schema = @Schema(implementation = User.class))
)
| 属性 | 含义 |
|---|---|
responseCode |
HTTP 状态码,如 200、400 |
description |
响应说明 |
content |
响应内容(使用 @Content 包装) |
5. @RequestBody(参数注解)
@RequestBody(
description = "请求体中的用户对象",
required = true
)
| 属性 | 含义 |
|---|---|
description |
请求体说明 |
required |
是否必填 |
使用示例整合
@Operation(
summary = "创建用户",
description = "根据请求体创建用户信息",
tags = {"用户管理"}
)
@ApiResponse(
responseCode = "201",
description = "创建成功",
content = @Content(schema = @Schema(implementation = User.class))
)
@PostMapping("/user")
public User createUser(
@RequestBody(
description = "用户信息",
required = true
)
User user
) {
return userService.create(user);
}
注:这里的@RequestBody导的包是
io.swagger.v3.oas.annotations.parameters.RequestBody,不是Spring MVC 提供的@RequestBody
欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1701220998@qq.com