当前位置: 首页 > news >正文

Swagger 在 Spring Boot 中的详细使用指南

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() {// 实现逻辑
}

四、常用注解详解

注解作用域描述
@TagController标记控制器,用于分组和描述
@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")));}));
}

七、最佳实践

  1. 保持文档同步:将 Swagger 注解作为代码的一部分维护

  2. 使用分组:大型项目按模块分组展示 API

  3. 提供完整示例:为每个模型属性添加 example 值

  4. 描述错误响应:详细描述可能的错误响应码和内容

  5. 结合测试:使用 Swagger 生成测试用例,确保文档准确性

  6. 版本控制:API 版本变更时同步更新文档版本

八、访问文档

启动应用后访问:

  • Swagger UI 界面http://localhost:8080/swagger-ui.html

  • OpenAPI JSONhttp://localhost:8080/v3/api-docs

九、常见问题解决

  1. 404 错误

    • 检查依赖是否正确添加

    • 确认 springdoc.api-docs.enabled=true

  2. 注解不生效

    • 检查包扫描范围

    • 确保使用正确的注解(io.swagger.v3.oas.annotations

  3. 模型属性未显示

    • 确保有公共 getter 方法

    • 或使用 @Schema 显式标注

  4. 日期格式问题

    java

    复制

    下载

    @Schema(type = "string", format = "date-time")
    private LocalDateTime createTime;

通过以上详细配置和注解使用,你可以为 Spring Boot 项目生成专业、易用的 API 文档,大大提高开发效率和协作质量。

http://www.lqws.cn/news/519805.html

相关文章:

  • thinkphp8之文件上传
  • 用户体验驱动的3D设计:从功能实现到情感共鸣的设计升级
  • 融合聚类与分类的退役锂电智能分选技术:助力新能源汽车产业可持续发展
  • JVM调优实战 Day 6:JVM性能监控工具实战
  • 数据结构 顺序表与链表
  • python的易家宜超市云购物系统
  • webman 利用tcp 做服务端 对接物联网
  • 使用 Spread.net将 Excel 中的文本拆分为多段
  • 注解+AOP+自动配置实现自定义starter
  • Java8 Stream流:Stream流的思想和获取Stream流
  • 深入浅出:RocketMQ与Kafka的双剑合璧,实现高可用与高吞吐
  • 服务器不支持PUT,DELETE 的解决方案
  • python爬虫框架scrapy学习记录
  • 打造属于你的AI智能体,从数据开始 —— 使用 Bright Data MCP+Trae快速构建垂直智能体
  • 量学云讲堂2025朱永海慢牛开启第58期视频课程
  • 卡萨帝发布AI深度科技:实现从守护生活到守护文明的升级
  • Linux系统之Nginx反向代理与缓存
  • Aurora MySQL 3.05/3.06/3.07版本即将停用,全局数据库升级实战指南
  • 逆序对的数量
  • 基于MATLAB的BP神经网络的心电图分类方法应用
  • pyhton基础【16】函数进阶二
  • 仿Apple官网设计风格
  • HCIA-IP路由基础
  • 鸿蒙OH南向开发 轻量系统内核(LiteOS-M)【Shell】
  • 实测对比:用 Lynx 做网页,效率比传统工具提升 270% 的底层逻辑
  • 【Oracle学习笔记】4.索引(Index)
  • 【大厂机试题解法笔记】可以组成网络的服务器
  • FPGA基础 -- Verilog 格雷码(Gray Code)计数器设计与原理解析
  • 开疆智能CCLinkIE转ModbusTCP网关连接脉冲计数器配置案例
  • MySQL之存储过程详解