@Operation vs @ApiResponse 在 Swagger 中的使用

REST,Spring
Remote
1
04:01 AM · Dec 01 ,2025

1. 概述

在本教程中,我們將討論 Swagger 的 @Operation@ApiResponse 註解之間的主要區別。

2. 使用 Swagger 進行描述性文檔

當我們創建 REST API 時,創建其適當的規範也同樣重要。 此外,這樣的規範應該易於閲讀、易於理解,並提供所有必要的信息。

此外,文檔應該描述對 API 所做的所有更改。 手動創建 REST API 文檔既耗時又費力。 幸運的是,像 Swagger 這樣的工具可以幫助我們完成這個過程。

Swagger 代表了一組圍繞 OpenAPI 規範構建的開源工具。 它能幫助我們設計、構建、文檔和消費 REST API。

Swagger 規範是 REST API 文檔的標準。 使用 Swagger 規範,我們可以描述整個 API,例如暴露的端點、操作、參數、身份驗證方法等。

Swagger 提供各種註釋,可以幫助我們文檔化 REST API。 此外,它還提供 @Operation@ApiResponse 註解,用於文檔化 REST API 的響應

在接下來的教程中,我們將使用下面的控制器類,並瞭解如何使用這些註解:

@RestController
@RequestMapping("/customers")
class CustomerController {

   private final CustomerService customerService;

   public CustomerController(CustomerService customerService) {
       this.customerService = customerService;
   }
  
   @GetMapping("/{id}")
   public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
       return ResponseEntity.ok(customerService.getById(id));
   }
}

3.

The annotation is used to describe a single operation. An operation is a unique combination of a path and an HTTP method.

Additionally, using , we can describe the result of a successful REST API call. In other words, we can use this annotation to specify the general return type.

Let’s add the annotation to our method:

@Operation(summary = "Gets customer by ID", 
           description= "Customer must exist")
@GetMapping("/{id}")
public ResponseEntity<CustomerResponse> getCustomer(@PathVariable("id") Long id) {
    return ResponseEntity.ok(customerService.getById(id));
}

Next, we’ll go through some of the most used properties within .

3.1. The Property

The required property contains the operation’s summary field. Simply put, it provides a short description of the operation. However, we should keep this parameter shorter than 120 characters.

Here’s how we define the summary property inside the annotation:

@Operation(summary= "Gets customer by ID")

3.2. The Property

Using , we can provide more details about the operation. For instance, we can place a text describing the endpoint’s restrictions:

@Operation(summary= "Gets customer by ID", description= "Customer must exist")

3.3.  The