最新版 springdoc-openapi-starter-webmvc-ui 常用注解详解 + 实战示例

当然可以!在 Spring Boot 3 + SpringDoc OpenAPI(Swagger 3 替代方案)生态中,springdoc-openapi-starter-webmvc-ui 是目前官方推荐的集成方式。它提供了一套丰富的注解,用于精细化控制 API 文档的生成,提升前端、测试、产品等协作方的体验。


最新版 springdoc-openapi-starter-webmvc-ui 常用注解详解 + 实战示例

📌 当前最新稳定版本:springdoc-openapi 2.5+(2025年仍适用)
📌 所有注解位于包:io.swagger.v3.oas.annotations.*

🧩 一、核心注解概览

注解作用适用位置
@OpenAPIDefinition全局 API 信息配置(标题、版本、联系人等)@Configuration
@Tag标记 Controller 或方法所属的“标签/模块”类、方法
@Operation描述某个 API 操作(方法)的详细信息方法
@Parameter描述单个请求参数(路径、查询、Header)方法参数
@Parameters批量描述多个参数方法
@RequestBody描述请求体结构方法参数
@ApiResponse描述单个响应状态码及结构方法
@ApiResponses批量描述多个响应方法
@Schema描述 DTO 字段的含义、示例、格式等类、字段、方法参数
@Hidden隐藏某个 Controller 或方法,不生成文档类、方法、字段

🧱 二、详细注解说明 + 实战示例(带中文注释)


1️⃣ @Tag —— 模块分组标签

用于对 Controller 或方法进行分组,前端文档左侧菜单按 Tag 分组显示。
@Tag(name ="用户管理模块", description ="提供用户增删改查、状态管理等核心功能")@RestController@RequestMapping("/api/users")publicclassUserController{// ...}

作用

  • 在 Swagger UI 左侧菜单中显示为“用户管理模块”。
  • 可用于模块化组织大型项目 API。

2️⃣ @Operation —— API 操作描述

描述某个接口的用途、注意事项、是否已废弃等。
@Operation( summary ="分页查询用户列表", description ="支持按用户名、年龄范围、状态筛选,返回分页数据。\n"+"createTime 字段为 ISO 格式,如:2025-04-01T10:00:00", tags ={"用户管理模块"},// 可覆盖类上的 Tag deprecated =false,// 是否废弃 security =@SecurityRequirement(name ="Bearer Token")// 安全要求(需配合 SecurityScheme))@GetMappingpublicResult<IPage<UserVO>>listUsers(@Parameter(description ="当前页码,从1开始", example ="1")@RequestParam(defaultValue ="1")Integer current,@Parameter(description ="每页大小,最大100", example ="10")@RequestParam(defaultValue ="10")Integer size,UserQueryDTO query){// ...}

作用

  • summary:接口简短标题(必填,显示在接口列表)
  • description:详细说明,支持 Markdown
  • deprecated:标记为废弃接口(UI 会显示删除线)
  • security:声明该接口需要认证(需全局配置 SecurityScheme)

3️⃣ @Parameter —— 单个参数描述

用于描述 @RequestParam, @PathVariable, @RequestHeader 等参数。
@GetMapping("/{id}")@Operation(summary ="根据ID获取用户详情")publicResult<UserVO>getUserById(@Parameter( name ="id", description ="用户唯一标识,雪花ID", required =true, example ="123456789012345678", schema =@Schema(type ="integer", format ="int64"))@PathVariableLong id){User user = userService.getById(id);if(user ==null){returnResult.error(404,"用户不存在");}returnResult.success(userStructMapper.toVO(user));}

作用

  • name:参数名(通常可省略,自动推断)
  • description:参数说明
  • required:是否必填
  • example:示例值(非常重要!前端可一键填充)
  • schema:指定数据类型和格式(如 int64、date-time、email 等)

4️⃣ @RequestBody —— 请求体描述

用于描述 @RequestBody 注解的 DTO 对象结构。
@PostMapping@Operation(summary ="创建新用户")publicResult<String>createUser(@io.swagger.v3.oas.annotations.parameters.RequestBody( description ="用户创建请求体", required =true, content =@Content( mediaType ="application/json", schema =@Schema(implementation =UserCreateDTO.class), examples ={@ExampleObject( name ="创建普通用户", value =""" { "name": "张三", "age": 25, "email": "[email protected]", "status": 1 } """),@ExampleObject( name ="创建未成年用户", value =""" { "name": "小明", "age": 16, "email": "[email protected]", "status": 0 } """)}))@Valid@RequestBodyUserCreateDTO createDTO){boolean saved = userService.createUser(createDTO);return saved ?Result.success("用户创建成功"):Result.error("创建失败");}

作用

  • description:请求体说明
  • content.schema.implementation:指定 DTO 类,自动生成字段文档
  • examples:提供多个示例(前端可切换使用)
  • 支持 JSON/YAML 示例
💡 注意:不要与 org.springframework.web.bind.annotation.RequestBody 混淆,这里是 io.swagger.v3.oas.annotations.parameters.RequestBody

5️⃣ @Schema —— 字段/类级描述(最常用!)

用于描述 DTO/Entity 的字段含义、格式、示例、是否只读等。
@Data@Schema(description ="用户创建请求参数")publicclassUserCreateDTO{@Schema( description ="用户名,2-20位中文或英文", example ="张三", minLength =2, maxLength =20, requiredMode =Schema.RequiredMode.REQUIRED // 必填)@NotBlank(message ="用户名不能为空")privateString name;@Schema( description ="年龄,0-150岁", example ="25", minimum ="0", maximum ="150", requiredMode =Schema.RequiredMode.REQUIRED )@NotNull(message ="年龄不能为空")@Min(value =0, message ="年龄不能小于0")privateInteger age;@Schema( description ="邮箱地址", example ="[email protected]", format ="email",// 格式校验提示 requiredMode =Schema.RequiredMode.NOT_REQUIRED )@Email(message ="邮箱格式不正确")privateString email;@Schema( description ="用户状态:0=禁用,1=启用", example ="1", allowableValues ={"0","1"},// 枚举值提示 requiredMode =Schema.RequiredMode.REQUIRED )@NotNull(message ="状态不能为空")privateInteger status;}

作用

  • 自动生成字段说明、示例、校验规则提示
  • format:支持 date, date-time, email, uuid, uri
  • allowableValues:枚举值提示(前端下拉可选)
  • accessMode:可设置 READ_ONLY(仅响应)或 WRITE_ONLY(仅请求,如密码字段)
  • implementation:用于嵌套对象或接口类型

6️⃣ @ApiResponse & @ApiResponses —— 响应结构描述

描述不同 HTTP 状态码对应的响应结构,特别是错误码。
@PutMapping@Operation(summary ="更新用户信息")@ApiResponses(value ={@ApiResponse( responseCode ="200", description ="更新成功", content =@Content(schema =@Schema(implementation =Result.class))),@ApiResponse( responseCode ="400", description ="参数校验失败", content =@Content(schema =@Schema(implementation =Result.class))),@ApiResponse( responseCode ="404", description ="用户不存在", content =@Content(schema =@Schema(implementation =Result.class))),@ApiResponse( responseCode ="500", description ="系统内部错误", content =@Content(schema =@Schema(implementation =Result.class)))})publicResult<String>updateUser(@Valid@RequestBodyUserUpdateDTO updateDTO){boolean updated = userService.updateUser(updateDTO);return updated ?Result.success("更新成功"):Result.error("更新失败");}

作用

  • 前端可预知不同状态码的响应结构
  • 配合全局异常处理器,可标准化错误返回
  • responseCode:HTTP 状态码
  • description:状态码含义
  • content.schema:指定响应体结构(通常为 Result<T>

7️⃣ @Hidden —— 隐藏接口或字段

隐藏不想暴露给前端的接口或敏感字段。
@Hidden// 整个 Controller 不生成文档@RestController@RequestMapping("/api/internal")publicclassInternalController{// ...}// 或隐藏某个字段(如密码、密钥)@DatapublicclassUserVO{privateLong id;privateString name;@Hidden// 不在 Swagger 中显示privateString internalCode;privateString email;}

作用

  • 隐藏内部接口(如运维、回调、定时任务触发接口)
  • 隐藏敏感字段(如密码、密钥、审计字段)

8️⃣ @OpenAPIDefinition —— 全局 API 信息配置

通常放在启动类或独立配置类中,定义 API 全局元信息。
@OpenAPIDefinition( info =@Info( title ="企业用户管理系统 API 文档", version ="v1.2.0", description ="提供用户管理、权限控制、操作日志等核心功能", contact =@Contact( name ="API支持团队", email ="[email protected]", url ="https://www.company.com"), license =@License( name ="Apache 2.0", url ="https://www.apache.org/licenses/LICENSE-2.0.html")), servers ={@Server(url ="http://localhost:8080", description ="本地开发环境"),@Server(url ="https://api.company.com", description ="生产环境")})@SpringBootApplication@MapperScan("com.example.demo.mapper")publicclassDemoApplication{publicstaticvoidmain(String[] args){SpringApplication.run(DemoApplication.class, args);}}

作用

  • 定义 API 标题、版本、描述、联系人、许可证
  • 定义多环境服务器地址(前端可切换)
  • 显示在 Swagger UI 顶部

9️⃣ @SecurityScheme + @SecurityRequirement —— 安全认证配置

配置 JWT/Bearer Token 认证方式。
@SecurityScheme( name ="Bearer Token", type =SecuritySchemeType.HTTP, bearerFormat ="JWT", scheme ="bearer"// 小写 bearer)@ConfigurationpublicclassOpenApiConfig{// 可放在此类,或与 @OpenAPIDefinition 合并}

然后在需要认证的接口上添加:

@Operation( summary ="删除用户", security =@SecurityRequirement(name ="Bearer Token")// 引用上面定义的 name)@DeleteMapping("/{id}")publicResult<String>deleteUser(@PathVariableLong id){// ...}

作用

  • Swagger UI 顶部会出现 🔒 认证按钮
  • 前端可输入 Token,后续请求自动带 Authorization: Bearer xxx
  • 提升 API 安全性和测试便利性

🧪 三、完整 Controller 示例(整合所有注解)

packagecom.example.demo.controller;importcom.example.demo.entity.dto.*;importcom.example.demo.entity.vo.UserVO;importcom.example.demo.service.IUserService;importcom.example.demo.util.Result;importcom.baomidou.mybatisplus.core.metadata.IPage;importcom.baomidou.mybatisplus.extension.plugins.pagination.Page;importio.swagger.v3.oas.annotations.Operation;importio.swagger.v3.oas.annotations.Parameter;importio.swagger.v3.oas.annotations.Parameters;importio.swagger.v3.oas.annotations.media.Content;importio.swagger.v3.oas.annotations.media.ExampleObject;importio.swagger.v3.oas.annotations.media.Schema;importio.swagger.v3.oas.annotations.responses.ApiResponse;importio.swagger.v3.oas.annotations.responses.ApiResponses;importio.swagger.v3.oas.annotations.security.SecurityRequirement;importio.swagger.v3.oas.annotations.tags.Tag;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.validation.annotation.Validated;importorg.springframework.web.bind.annotation.*;importjavax.validation.Valid;importjavax.validation.constraints.Min;importjavax.validation.constraints.NotNull;@Tag(name ="用户管理模块", description ="提供用户增删改查、状态管理、批量操作等核心功能")@Validated@RestController@RequestMapping("/api/users")publicclassUserController{@AutowiredprivateIUserService userService;@AutowiredprivateUserStructMapper userStructMapper;// ==================== 查询 ====================@Operation( summary ="分页查询用户列表", description =""" 支持多条件组合查询: - 按用户名模糊匹配 - 按年龄范围筛选 - 按状态精确匹配 - 按创建时间区间筛选 返回标准分页结构。 """, security =@SecurityRequirement(name ="Bearer Token"))@Parameters({@Parameter(name ="current", description ="当前页码,从1开始", example ="1", required =true),@Parameter(name ="size", description ="每页大小,建议10~50", example ="10", required =true)})@ApiResponses({@ApiResponse(responseCode ="200", description ="查询成功", content =@Content(schema =@Schema(implementation =Result.class))),@ApiResponse(responseCode ="401", description ="未授权", content =@Content(schema =@Schema(implementation =Result.class)))})@GetMappingpublicResult<IPage<UserVO>>listUsers(@Min(1)@RequestParam(defaultValue ="1")Integer current,@Min(1)@RequestParam(defaultValue ="10")Integer size,UserQueryDTO query){Page<User> page =newPage<>(current, size);IPage<User> userPage = userService.searchUsers(query, page);List<UserVO> voList = userStructMapper.toVOList(userPage.getRecords());IPage<UserVO> voPage =newPage<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal()); voPage.setRecords(voList);returnResult.success(voPage);}// ==================== 创建 ====================@Operation( summary ="创建新用户", description ="创建用户时会自动填充创建时间,状态默认启用")@io.swagger.v3.oas.annotations.parameters.RequestBody( description ="用户创建请求体", required =true, content =@Content( mediaType ="application/json", schema =@Schema(implementation =UserCreateDTO.class), examples ={@ExampleObject( name ="成人用户", value =""" { "name": "张三", "age": 25, "email": "[email protected]", "status": 1 } """),@ExampleObject( name ="未成年用户", value =""" { "name": "小明", "age": 16, "email": "[email protected]", "status": 0 } """)}))@PostMappingpublicResult<String>createUser(@Valid@RequestBodyUserCreateDTO createDTO){boolean saved = userService.createUser(createDTO);return saved ?Result.success("用户创建成功"):Result.error("创建失败");}// ==================== 更新 ====================@Operation(summary ="更新用户信息")@PutMappingpublicResult<String>updateUser(@Valid@RequestBodyUserUpdateDTO updateDTO){boolean updated = userService.updateUser(updateDTO);return updated ?Result.success("更新成功"):Result.error("更新失败");}// ==================== 删除 ====================@Operation( summary ="删除用户(逻辑删除)", description ="不会物理删除数据,仅标记 deleted=1", security =@SecurityRequirement(name ="Bearer Token"))@Parameter(name ="id", description ="用户ID", required =true, example ="123456789012345678")@DeleteMapping("/{id}")publicResult<String>deleteUser(@PathVariable@NotNullLong id){boolean deleted = userService.removeById(id);return deleted ?Result.success("删除成功"):Result.error("用户不存在或已被删除");}}

✅ 四、最佳实践建议

实践项说明
所有公开接口必须加 @Operation至少写 summary,让前端知道接口用途
DTO 字段必须加 @Schema描述 + 示例 + 校验规则,极大提升协作效率
关键参数加 @Parameter(example=...)前端可一键填充测试数据
提供多个 @ExampleObject覆盖正常、边界、异常场景
敏感接口加 @SecurityRequirement明确告知需要 Token
废弃接口加 deprecated = true前端可见,避免误用
内部接口用 @Hidden避免文档混乱
全局配置 @OpenAPIDefinition统一团队 API 文档风格

🌐 五、访问与调试

  • 文档地址:http://localhost:8080/swagger-ui/index.html
  • OpenAPI JSON:http://localhost:8080/v3/api-docs
  • 支持 Try it out → 在线调试 → 自动生成 Curl/Request

✅ 六、总结

通过合理使用 SpringDoc OpenAPI 注解,你可以:

✅ 生成专业级、可交互、可调试的 API 文档
减少前后端沟通成本,提升开发效率
标准化接口设计,避免“口口相传”
提升项目专业度和可维护性

💡 提示:注解虽好,但不要过度堆砌。保持简洁、实用、一致即可。大型项目建议制定《API 文档规范》,统一注解使用标准。

📌 官方文档参考:https://springdoc.org/


这份指南涵盖了企业开发中 95% 以上的 SpringDoc 注解使用场景,可直接用于生产项目!

Read more

Anaconda安装(2024最新版)

Anaconda安装(2024最新版)

安装新的anaconda需要卸载干净上一个版本的anaconda,不然可能会在新版本安装过程或者后续使用过程中出错,完全卸载干净anaconda的方法,可以参考我的博客! 第一步:下载anaconda安装包         官网:Anaconda | The Operating System for AI (不过官网是外网,这里推荐国内清华大学的镜像源,对于国内的网络友好,下载速度更快!) 清华镜像网:Index of /anaconda/archive/ | 清华大学开源软件镜像站 | Tsinghua Open Source MirrorIndex of /anaconda/archive/ | 清华大学开源软件镜像站,致力于为国内和校内用户提供高质量的开源软件镜像、Linux 镜像源服务,帮助用户更方便地获取开源软件。本镜像站由清华大学 TUNA 协会负责运行维护。https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/         这里有许多版本,博主这些选择下载最新版本的2024.06-1版本

By Ne0inhk

关于 ComfyUI 的 Windows 本地部署系统环境教程(详细讲解Windows 10/11、NVIDIA GPU、Python、PyTorch环境等)

在本地部署 ComfyUI 时,确保 Python、PyTorch、CUDA 等组件的版本能完美匹配,这对避免安装报错和保证稳定运行至关重要。 以下内容是整合了一份核心组件的版本适配对照表,并配上不同显卡的配置建议,希望能帮助你顺利部署。 一、准备阶段 1. 系统与硬件确认 * 确保你的系统为 Windows 10 或更高版本。 * 拥有一块 NVIDIA 显卡(最好支持较新 CUDA 架构)。 * 显存建议至少 6-8 GB,如果你要做高清、大分辨率或多插件 (ControlNet/LoRA) 的生成,建议 12 GB 以上。 * NVIDIA 驱动建议更新为与所选 CUDA 版本兼容的最新驱动。 * 你可运行 nvidia-smi 在终端查看当前驱动版本及支持的 CUDA 最高版本。 * 硬盘建议为 SSD,并有充足可用空间(

By Ne0inhk
【探讨】Python 虚拟环境迁移难题:如何让 .venv 随项目文件夹随意搬家也不坏?

【探讨】Python 虚拟环境迁移难题:如何让 .venv 随项目文件夹随意搬家也不坏?

【探讨】Python 虚拟环境迁移难题:如何让 .venv 随项目文件夹随意搬家也不坏? 【探讨】“父级/基环境损坏,子环境全部失效”,如何避免 .venv 受父级 Python 损坏影响? 在日常 Python 开发中,我们经常会遇到这样的场景: * 把项目文件夹从公司电脑复制到家用电脑继续开发 * 在不同磁盘、不同目录间移动项目 * 把项目分享给同事或朋友,让他们直接运行 * 在服务器上部署时直接复制整个项目目录 这时最让人头疼的问题就是:用 python -m venv .venv 创建的虚拟环境,在迁移后往往直接“坏掉”——激活后运行 python 报错“command not found”,或者提示找不到解释器。 为什么会这样?有没有彻底解决的办法?本文将从问题根源出发,系统分析各种方案的优劣,并给出最实用的推荐。 问题根源:标准 venv 为什么不可迁移?

By Ne0inhk
抽奖系统Selenium自动化测试流程解析

抽奖系统Selenium自动化测试流程解析

🌈感谢大家的阅读、点赞、收藏和关注  💕希望大家喜欢我本次的讲解💕 目录👑 一、自动化测试环境与框架核心配置🌟 1. 技术栈与依赖(测试文档 - 环境配置章节) 2. 浏览器驱动初始化(测试文档 - 基础工具章节) 二、核心工具类(测试文档 - 通用工具章节)❄️ 1. 测试数据自动生成(解决测试数据重复问题) 2. 自动化截图(测试失败溯源) 三、核心业务模块测试逻辑(测试文档 - 功能测试章节)🍃 1. 登录 / 注册模块(边界值 + 异常场景全覆盖) 2. 管理员核心模块(iframe 切换 + 多场景校验) 3. 测试执行入口(全流程自动化) 四、关键技术难点与解决方案(测试文档 -

By Ne0inhk