swwagger3中的@Tag @Operation @Schema的作用是什么?

本文详细解释了Swagger中@Tag、@Operation和@Schema注解的作用,分别用于描述API、操作和数据模型,以及如何在Java中使用它们来组织和文档化RESTAPI接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在 Swagger 中,@Tag@Operation 和 @Schema 是用于描述 REST API 的注解。

  1. @Operation 注解

    • @Operation 用于描述单个操作(即 API 端点)。
    • 最常用的属性包括:
      • summary:表示操作的摘要,通常不要太长。
      • description:用于描述操作的细节,例如限制、返回值等。
      • hidden:表示是否隐藏此 API。
    • 示例:Java

      @Operation(summary = "获取客户信息", description = "客户必须存在")
      @GetMapping("/{id}")
      public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
          // 实现逻辑...
      }
      
  2. @ApiResponse 注解

    • 通常,不同的业务状态会返回不同的 HTTP 状态码。@ApiResponse 用于描述 API 可能会返回的具体响应和状态码。
    • 可以应用于方法上或类上,方法上的注解优先于类上注解。
    • 必须将其定义在 @ApiResponses 注解中才会生效。
    • 示例:Java

      @ApiResponses(value = {
          @ApiResponse(responseCode = "200", description = "成功", content = {
              @Content(mediaType = "application/json", schema = @Schema(implementation = CustomerResponse.class))
          }),
          @ApiResponse(responseCode = "400", description = "无效的 ID"),
          @ApiResponse(responseCode = "404", description = "客户不存在"),
          @ApiResponse(responseCode = "500", description = "内部服务器错误", content = {
              @Content(mediaType = "application/json", schema = @Schema(implementation = ErrorResponse.class))
          })
      })
      @GetMapping("/{id}")
      public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
          // 实现逻辑...
      }
      
  3. @Schema 注解

    • 用于描述数据模型(例如请求体或响应体)的结构。
    • 可以应用于类、字段或方法参数上。
    • 示例:Java

      @Schema(description = "客户信息")
      public class CustomerResponse {
          // 属性定义...
      }
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值