最新版 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

trae整合figma的mcp实现前端代码自动生成

1.现在trae版本在3.0及以上版本。 2.trae账号是企业版。 3.打开设置,找到mcp 这里需要token,需要从figma账号里生成,网页登录figma账号,找到设置,打开后找到security,然后点击generate new token,token名称随便取,权限都钩上。然后生成一个token,把token放到mcp中即可。 4.使用mcp,切换到mcp模式,你也可以自己创建智能体使用 5.提问使用,可参考下面的提示词使用 注意:这里面的figma链接是mcp的链接,不是figma链接,一般需要你有原型的权限才能看到 我需要根据提供的Figma链接生成一个与设计稿高度一致的网页。请严格遵循以下详细要求:

By Ne0inhk

AI在前端工作中的应用

AI在前端工作中的应用 在AI的高速发展中,也离不开前端,前端开发也在AI工具中发挥着举足轻重的作用。同时,一些AI工具也是的前端开发工作提效不少,合理利用工具,能在工作中提升效率。本文介绍一些前端与AI结合的场景,不限于接入,也包含一些工具的使用。 1、自定义GPT场景 在自定义 GPT 场景中,前端的核心职责是搭建 “用户 - 自定义 GPT” 的交互入口,同时支撑 GPT 的个性化配置、功能扩展与数据可视化,需围绕 “交互体验、配置能力、集成适配” 三大核心展开工作。 ant-design提供给前端开发者快速开发AI相关的UI组件库:https://ant-design-x.antgroup.com * SSE SSE是一种基于HTTP协议的数据传输方式,它允许服务端向客户端推送数据。前端可以通过SSE实现GPT的实时对话,用户输入问题,GPT返回结果。为什么选择这种方式,是因为GPT返回结果是很漫长的,所以用流式传入,能让用户体验更友好,不用websocket是因为长连接占用资源过多,服务器长连接数有限,所以用SSE。 可以直接使用微软的SSE库:

By Ne0inhk
旧安卓手机别扔!用KSWEB搭个人博客,搭配外网访问超香

旧安卓手机别扔!用KSWEB搭个人博客,搭配外网访问超香

KSWEB 作为安卓端轻量级 Web 服务器,核心功能是提供 PHP、MySQL 运行环境,能轻松部署 Typecho、WordPress 等博客系统,Termux 则可辅助管理内网穿透服务;这类工具特别适合预算有限的学生、个人博主,或是想折腾闲置设备的数码爱好者,优点也很突出 —— 对硬件要求极低,1GB 内存就能运行,旧款红米、华为畅享等机型都能适配,而且内置的运行环境无需手动配置,新手也能快速上手。 使用这套工具时也有不少需要注意的地方,比如手机要长期插电并连接稳定 Wi-Fi,否则服务容易中断;还要给 KSWEB 和 Termux 关闭电池优化、放开存储权限,我用小米手机测试时就因为没关后台限制,导致 Apache 服务频繁被系统杀掉,折腾了好一会儿才排查出问题;另外非 Root 机型也能使用,但部分文件权限操作会稍显繁琐。 不过仅靠 KSWEB 部署完博客后,只能在局域网内访问,这会带来很多不便:比如在家用电脑能连手机看博客,

By Ne0inhk
LangChain 消息处理全解析:缓存、过滤、合并与流式输出实战

LangChain 消息处理全解析:缓存、过滤、合并与流式输出实战

文章目录 * 一、消息内存缓存 * 核心概念 * 关键组件 * 代码流程 * 运行效果 * 二、消息过滤 * 核心概念 * 关键函数 * 过滤参数 * 代码示例 * 过滤逻辑 * 三、消息合并 * 核心概念 * 关键函数 * 代码示例 * 合并效果 * 两种使用方式 * 四、流式输出 * 什么是流式输出 * 为什么需要? * 典型应用 * 五、同步 vs 异步流式 * 核心区别 * 工作原理 * 何时使用异步? * 六、流式输出基础用法 * 同步流式 * 异步流式 * 七、输出解析器 * 八、流式输出实际应用 * 1. 聊天机器人 * 2. 多用户并发 * 3. FastAPI 集成 * 九、常见问题

By Ne0inhk