Spring Boot 3 集成 Swagger 3 完整指南
Swagger(现更名为OpenAPI)是一个用于设计、构建和文档化API的强大工具。在Spring Boot 3中集成Swagger 3(OpenAPI 3.0)可以帮助我们自动生成API文档,方便前后端开发人员协作。
一、依赖配置
首先,在pom.xml中添加SpringDoc OpenAPI依赖(Swagger 3的官方实现):
1 2 3 4 5 6
| <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.1.0</version> </dependency>
|
这个依赖包含了:
- OpenAPI 3.0规范的实现
- Swagger UI界面
- 与Spring Boot 3的自动配置
二、基本配置
创建Swagger配置类,自定义API文档信息:
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
| package com.example.demo.config;
import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Contact; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
@Configuration public class SwaggerConfig {
@Bean public OpenAPI customOpenAPI() { return new OpenAPI() .info(new Info() .title("Spring Boot 3 API 文档") .version("1.0.0") .description("这是一个使用Spring Boot 3和Swagger 3构建的API文档示例") .termsOfService("https://example.com/terms") .contact(new Contact() .name("开发团队") .email("dev@example.com") .url("https://example.com")) .license(new License() .name("Apache 2.0") .url("https://www.apache.org/licenses/LICENSE-2.0.html"))); } }
|
三、实战示例
1. 创建实体类
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
| package com.example.demo.model;
import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor;
@Data @NoArgsConstructor @AllArgsConstructor @Schema(description = "用户实体类") public class User { @Schema(description = "用户ID", example = "1") private Long id; @Schema(description = "用户名", example = "张三") private String username; @Schema(description = "用户年龄", example = "25") private Integer age; @Schema(description = "用户邮箱", example = "zhangsan@example.com") private String email; }
|
2. 创建控制器
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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package com.example.demo.controller;
import com.example.demo.model.User; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.tags.Tag; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap;
@RestController @RequestMapping("/api/users") @Tag(name = "用户管理", description = "用户CRUD操作的API接口") public class UserController {
private static final ConcurrentHashMap<Long, User> users = new ConcurrentHashMap<>(); static { users.put(1L, new User(1L, "张三", 25, "zhangsan@example.com")); users.put(2L, new User(2L, "李四", 30, "lisi@example.com")); }
@GetMapping @Operation(summary = "获取所有用户", description = "返回系统中所有的用户列表") @ApiResponse(responseCode = "200", description = "查询成功", content = @Content(schema = @Schema(implementation = User.class))) public List<User> getAllUsers() { return new ArrayList<>(users.values()); }
@GetMapping("/{id}") @Operation(summary = "根据ID获取用户", description = "根据用户ID查询用户信息") @ApiResponse(responseCode = "200", description = "查询成功") @ApiResponse(responseCode = "404", description = "用户不存在") public ResponseEntity<User> getUserById( @Parameter(name = "id", description = "用户ID", in = ParameterIn.PATH, required = true) @PathVariable Long id) { User user = users.get(id); if (user == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(user); }
@PostMapping @Operation(summary = "创建新用户", description = "添加新用户到系统中") @ApiResponse(responseCode = "201", description = "用户创建成功") public ResponseEntity<User> createUser( @Parameter(description = "用户信息", required = true) @RequestBody User user) { Long newId = users.size() + 1L; user.setId(newId); users.put(newId, user); return ResponseEntity.status(201).body(user); }
@PutMapping("/{id}") @Operation(summary = "更新用户信息", description = "根据ID更新用户信息") public ResponseEntity<User> updateUser( @Parameter(name = "id", description = "用户ID", in = ParameterIn.PATH, required = true) @PathVariable Long id, @Parameter(description = "更新后的用户信息", required = true) @RequestBody User user) { if (!users.containsKey(id)) { return ResponseEntity.notFound().build(); } user.setId(id); users.put(id, user); return ResponseEntity.ok(user); }
@DeleteMapping("/{id}") @Operation(summary = "删除用户", description = "根据ID删除用户") public ResponseEntity<Void> deleteUser( @Parameter(name = "id", description = "用户ID", in = ParameterIn.PATH, required = true) @PathVariable Long id) { if (!users.containsKey(id)) { return ResponseEntity.notFound().build(); } users.remove(id); return ResponseEntity.noContent().build(); } }
|
四、常用Swagger注解说明
| 注解 | 说明 |
|---|
@Tag | 用于描述控制器类的作用 |
@Operation | 用于描述接口方法的作用 |
@Parameter | 用于描述方法参数 |
@Schema | 用于描述实体类或属性 |
@ApiResponse | 用于描述接口的响应信息 |
@RequestBody | 用于描述请求体参数 |
五、访问Swagger UI
启动Spring Boot应用后,通过以下地址访问Swagger UI界面:
1
| http://localhost:8080/swagger-ui/index.html
|
在这个界面中,你可以:
- 查看所有API接口列表
- 查看每个接口的详细信息(参数、响应等)
- 在线测试API接口
- 导出API文档(支持JSON和YAML格式)
六、生产环境配置
在生产环境中,我们通常需要关闭Swagger文档,可以通过配置文件实现:
1 2 3 4 5 6
| springdoc: api-docs: enabled: false swagger-ui: enabled: false
|
然后在启动时指定生产环境:
1
| java -jar your-app.jar --spring.profiles.active=prod
|
七、其它参数配置案例
1.多个路径参数(@PathVariable)
适用于 URL 路径中包含多个占位符的情况(如 /users/{userId}/orders/{orderId})。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @GetMapping("/users/{userId}/orders/{orderId}") public ResponseEntity<Order> getOrder( // 第一个路径参数:用户ID @Parameter(name = "userId", description = "用户ID", in = ParameterIn.PATH, required = true) @PathVariable Long userId, // 第二个路径参数:订单ID @Parameter(name = "orderId", description = "订单ID", in = ParameterIn.PATH, required = true) @PathVariable Long orderId ) { Order order = orderService.getOrder(userId, orderId); return ResponseEntity.ok(order); }
|
说明:
- 路径中用 {参数名} 定义占位符,方法参数通过 @PathVariable 依次绑定;
- 参数名需与路径占位符一致,不一致时需指定 @PathVariable(“占位符名称”)。
2. 多个查询参数(@RequestParam)
适用于 URL 中以 ?key=value&key2=value2 形式传递的参数(如 /users?page=1&size=10&keyword=test)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @GetMapping("/users") public ResponseEntity<Page<User>> getUsers( // 分页参数:页码(默认值1) @Parameter(name = "page", description = "页码", in = ParameterIn.QUERY, required = false) @RequestParam(defaultValue = "1") Integer page, // 分页参数:每页条数(默认值10) @Parameter(name = "size", description = "每页条数", in = ParameterIn.QUERY, required = false) @RequestParam(defaultValue = "10") Integer size, // 查询关键词(非必填) @Parameter(name = "keyword", description = "查询关键词", in = ParameterIn.QUERY, required = false) @RequestParam(required = false) String keyword ) { Page<User> userPage = userService.findUsers(page, size, keyword); return ResponseEntity.ok(userPage); }
|
说明:
- 用 @RequestParam 绑定查询参数,required = false 表示非必填;
- defaultValue 可设置默认值(当参数未传递时使用)。
需使用 @RequestParam(“file”) MultipartFile file 接收文件,其他普通字段仍用 @RequestParam 或实体类。
1 2 3 4 5 6 7 8 9 10 11 12 13
| @PostMapping(value = "/user/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String uploadForm( // 接收文件 @Parameter(description = "头像文件") @RequestParam("avatar") MultipartFile avatar, // 接收普通表单字段(或用实体类接收) @Parameter(description = "用户名") @RequestParam String username ) { return "文件:" + avatar.getOriginalFilename() + ",用户:" + username; }
|
说明:
- 带文件的表单(multipart/form-data),需使用 @RequestParam(“file”) MultipartFile file 接收文件
4. 复杂参数(实体类接收)
当参数较多(如创建用户时需要 username、age、email 等),推荐用实体类统一接收(适用于 POST/PUT 等请求的请求体)。
1).定义实体类
1 2 3 4 5 6 7 8 9 10 11
| @Data public class UserDTO { @ApiModelProperty(value = "用户名", required = true) private String username; @ApiModelProperty(value = "年龄", required = false) private Integer age; @ApiModelProperty(value = "邮箱", required = true) private String email; }
|
2).在接口中使用实体类接收参数
1 2 3 4 5 6 7 8 9 10
| @PostMapping("/users") public ResponseEntity<User> createUser( // 请求体参数:用@RequestBody绑定实体类 @Parameter(description = "用户信息") @RequestBody @Valid UserDTO userDTO // @Valid用于参数校验 ) { User user = userService.createUser(userDTO); return ResponseEntity.status(HttpStatus.CREATED).body(user); }
|
说明:
- 用 @RequestBody 将请求体(通常是 JSON)转换为实体类对象;
- 结合 Swagger 的 @ApiModelProperty 注解,可在文档中展示每个字段的说明;
- @Valid 配合 javax.validation 注解(如 @NotBlank)可实现参数校验。
总结
通过以上步骤,我们完成了Spring Boot 3与Swagger 3的集成,实现了API文档的自动生成和在线测试功能。Swagger不仅能提高团队协作效率,还能作为API的活文档,随着代码的更新而自动更新。
在实际项目中,可以根据需要进一步定制Swagger配置,如添加全局参数、配置API分组、设置安全认证等,以满足不同场景的需求。