Swagger 是一个强大的 API 文档生成工具,在 Spring Boot 项目中主要通过 springdoc-openapi
库实现。下面我将详细讲解 Swagger 的配置、注解使用和高级功能。
一、基础配置
1. 添加依赖
在 pom.xml
中添加:
xml
复制
下载
运行
<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId><version>2.5.0</version> <!-- 检查最新版本 --> </dependency>
2. 基础配置(application.properties)
properties
复制
下载
# 启用 Swagger springdoc.api-docs.enabled=true# 文档基本信息配置 springdoc.swagger-ui.path=/swagger-ui.html springdoc.api-docs.path=/v3/api-docs springdoc.info.title=订单管理系统 API springdoc.info.description=订单管理系统的 RESTful API 文档 springdoc.info.version=1.0.0 springdoc.info.contact.name=技术支持 springdoc.info.contact.email=support@example.com springdoc.info.license.name=Apache 2.0 springdoc.info.license.url=https://www.apache.org/licenses/LICENSE-2.0
二、核心注解使用
1. Controller 层注解
java
复制
下载
@RestController @RequestMapping("/api/orders") @Tag(name = "订单管理", description = "订单的创建、查询和管理操作") public class OrderController {@Operation(summary = "创建新订单",description = "创建一个新的订单记录",responses = {@ApiResponse(responseCode = "201", description = "订单创建成功"),@ApiResponse(responseCode = "400", description = "无效的输入")})@PostMappingpublic ResponseEntity<Order> createOrder(@RequestBody @Valid @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "订单对象",required = true,content = @Content(schema = @Schema(implementation = Order.class))Order order) {// 实现逻辑}@Operation(summary = "根据ID获取订单",description = "通过订单ID获取订单详细信息")@GetMapping("/{id}")public Order getOrderById(@Parameter(name = "id",description = "订单ID",required = true,example = "12345")@PathVariable Long id) {// 实现逻辑}@Operation(summary = "分页查询订单",description = "根据条件分页查询订单列表")@GetMappingpublic Page<Order> getOrders(@Parameter(description = "页码,从0开始", example = "0") @RequestParam(defaultValue = "0") int page,@Parameter(description = "每页记录数", example = "10") @RequestParam(defaultValue = "10") int size,@Parameter(description = "排序字段,格式: field[,asc|desc]") @RequestParam(required = false) String sort) {// 实现逻辑} }
2. 模型类注解
java
复制
下载
@Schema(description = "订单实体") public class Order {@Schema(description = "订单ID", example = "1001")private Long id;@Schema(description = "订单状态", allowableValues = {"CREATED", "PAID", "SHIPPED", "COMPLETED", "CANCELLED"},example = "CREATED")private String status;@Schema(description = "订单总金额", example = "199.99")private BigDecimal totalAmount;@Schema(description = "创建时间", example = "2023-10-01T12:00:00Z")private LocalDateTime createdAt;// Getter/Setter }
3. 枚举类型注解
java
复制
下载
@Schema(description = "订单状态枚举") public enum OrderStatus {@Schema(description = "已创建")CREATED,@Schema(description = "已支付")PAID,@Schema(description = "已发货")SHIPPED,@Schema(description = "已完成")COMPLETED,@Schema(description = "已取消")CANCELLED }
三、高级配置
1. 自定义全局配置类
java
复制
下载
@Configuration public class SwaggerConfig {@Beanpublic OpenAPI customOpenAPI() {return new OpenAPI().info(new Info().title("订单管理系统 API").version("1.0.0").description("订单管理系统的 RESTful API 文档").contact(new Contact().name("技术支持").email("support@example.com")).license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0"))).externalDocs(new ExternalDocumentation().description("项目 Wiki 文档").url("https://wiki.example.com")).addSecurityItem(new SecurityRequirement().addList("bearerAuth")).components(new Components().addSecuritySchemes("bearerAuth", new SecurityScheme().name("bearerAuth").type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));} }
2. 分组配置
java
复制
下载
@Bean public GroupedOpenApi adminApi() {return GroupedOpenApi.builder().group("admin").pathsToMatch("/api/admin/**").build(); }@Bean public GroupedOpenApi publicApi() {return GroupedOpenApi.builder().group("public").pathsToMatch("/api/public/**").build(); }
3. 安全配置(JWT 示例)
java
复制
下载
@Operation(summary = "获取用户信息", security = {@SecurityRequirement(name = "bearerAuth")}) @GetMapping("/me") public User getCurrentUser() {// 实现逻辑 }
四、常用注解详解
注解 | 作用域 | 描述 |
---|---|---|
@Tag | Controller | 标记控制器,用于分组和描述 |
@Operation | 方法 | 描述 API 操作(GET/POST/PUT/DELETE 等) |
@Parameter | 参数 | 描述方法参数(路径参数、查询参数等) |
@RequestBody | 参数 | 描述请求体内容 |
@ApiResponse | 方法 | 描述操作的可能响应 |
@Schema | 模型类/属性 | 描述数据模型及其属性 |
@Hidden | 类/方法/属性 | 从文档中隐藏指定的元素 |
@SecurityRequirement | 方法 | 声明操作所需的安全方案 |
五、Swagger UI 高级功能
1. 自定义 UI 配置
properties
复制
下载
# 自定义 UI 路径 springdoc.swagger-ui.path=/custom-swagger# 禁用 Try It Out 功能 springdoc.swagger-ui.supportedSubmitMethods=# 默认展开深度 springdoc.swagger-ui.docExpansion=none# 自定义主题 springdoc.swagger-ui.configUrl=/swagger-config
2. 添加全局请求头
java
复制
下载
@Bean public OpenApiCustomiser customerGlobalHeaderOpenApiCustomiser() {return openApi -> openApi.getPaths().values().stream().flatMap(pathItem -> pathItem.readOperations().stream()).forEach(operation -> {operation.addParametersItem(new HeaderParameter().$ref("#/components/parameters/myGlobalHeader"));}); }
六、生产环境注意事项
1. 禁用 Swagger UI
properties
复制
下载
# 生产环境禁用 Swagger UI springdoc.swagger-ui.enabled=false springdoc.api-docs.enabled=false
2. 条件启用配置
java
复制
下载
@Profile({"dev", "test"}) @Configuration public class SwaggerConfig {// 只在 dev/test 环境启用 }
3. 安全保护
java
复制
下载
@Bean public OpenApiCustomiser securityOpenApiCustomiser() {return openApi -> openApi.getPaths().values().forEach(pathItem ->pathItem.readOperations().forEach(operation -> {operation.setSecurity(Collections.singletonList(new SecurityRequirement().addList("basicAuth")));})); }
七、最佳实践
-
保持文档同步:将 Swagger 注解作为代码的一部分维护
-
使用分组:大型项目按模块分组展示 API
-
提供完整示例:为每个模型属性添加
example
值 -
描述错误响应:详细描述可能的错误响应码和内容
-
结合测试:使用 Swagger 生成测试用例,确保文档准确性
-
版本控制:API 版本变更时同步更新文档版本
八、访问文档
启动应用后访问:
-
Swagger UI 界面:
http://localhost:8080/swagger-ui.html
-
OpenAPI JSON:
http://localhost:8080/v3/api-docs
九、常见问题解决
-
404 错误:
-
检查依赖是否正确添加
-
确认
springdoc.api-docs.enabled=true
-
-
注解不生效:
-
检查包扫描范围
-
确保使用正确的注解(
io.swagger.v3.oas.annotations
)
-
-
模型属性未显示:
-
确保有公共 getter 方法
-
或使用
@Schema
显式标注
-
-
日期格式问题:
java
复制
下载
@Schema(type = "string", format = "date-time") private LocalDateTime createTime;
通过以上详细配置和注解使用,你可以为 Spring Boot 项目生成专业、易用的 API 文档,大大提高开发效率和协作质量。