当前位置: 首页 > 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.lryc.cn/news/575219.html

相关文章:

  • PDF处理控件Spire.PDF系列教程:Python中快速提取PDF文本、表格、图像及文档信息
  • Python 数据分析与可视化 Day 7 - 可视化整合报告实战
  • 视频中的开放世界目标计数
  • gitbash中执行命令巨慢
  • 淘宝API安全合规指南:避免数据泄露与封禁
  • AI助教来袭:用n8n和Gemini搭建英语作文自动批阅与学情分析系统
  • 【网站内容安全检测】之2:从网站所有URL页面中提取所有外部及内部域名信息
  • request这个包中,get 这个方法里传入的是params ,post这个方法里传入的是data 和 json。这个区别是什么?
  • 每日AI资讯速递 | 2025-06-25
  • 深入理解 Spring 框架的 Bean 管理与 IOC​
  • 车牌识别与标注:基于百度OCR与OpenCV的实现(一)
  • (C++)vector数组相关基础用法(C++教程)(STL库基础教程)
  • MiniMax-M1混合MoE大语言模型(本地运行和私有化搭建)
  • 数据结构 顺序表与链表
  • 深入学习入门--(一)前备知识
  • C++11原子操作:从入门到精通
  • 从数据到决策:UI前端如何利用数字孪生技术提升管理效率?
  • Webpack 构建过程详解
  • Web层注解
  • python学习笔记(深度学习)
  • FPGA基础 -- Verilog 格雷码(Gray Code)计数器设计与原理解析
  • 【网站内容安全检测】之3:获取所有外部域名访问后图像
  • ABP VNext + Ocelot API 网关:微服务统一入口与安全策略
  • Boosting:从理论到实践——集成学习中的偏差征服者
  • webman 利用tcp 做服务端 对接物联网
  • 机器学习×第十五卷:集成学习下篇——她开始构建每一轮更接近你的贴靠路径(XGBoost)
  • 基于STM32的个人健康助手的设计
  • Containerd 容器技术
  • 基于Hp感染的慢性胃炎居家管理小程序的设计与实现(消息震动)
  • LVS-DR负载均衡群集深度实践:高性能架构设计与排障指南