知識庫 / REST RSS 訂閱

Swagger Codegen 自定義驗證

REST
HongKong
8
03:42 AM · Dec 06 ,2025

1. 概述

當我們需要使用 Swagger 生成驗證時,我們通常使用基本的規範(基本規範)。但是,我們可能需要添加 Spring 自定義驗證註解。

本教程將教你如何使用這些驗證來生成模型和 REST API,重點關注 OpenAPI 服務器生成器,而不是約束驗證器。

2. 安裝配置

為了安裝配置,我們將參考之前的 Baeldung 教程,使用 OpenAPI 3.0.0 定義生成服務器。接下來,我們將添加自定義驗證註解以及所有必要的依賴項。

3. PetStore API OpenAPI 定義

假設我們有 PetStore API 的 OpenAPI 定義,並且需要為 REST API 和描述的模型 Pet 添加自定義驗證。

3.1. API 模型自定義驗證

為了創建寵物,我們需要讓 Swagger 使用我們自定義的驗證註解來測試寵物的名稱是否大寫。因此,為了本教程的目的,我們將簡單地將其稱為 Capitalized

觀察下例中的 x-constraints 規範。只需讓 Swagger 知道我們需要生成另一種類型的註解即可:

openapi: 3.0.1
info:
  version: "1.0"
  title: PetStore
paths:
  /pets:
    post:
      #.. post described here
components:
  schemas:
    Pet:
      type: object
      required:
        - id
        - name
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
          x-constraints: "Capitalized(required = true)"
        tag:
          type: string

3.2. 為 REST API 端點自定義驗證

如上所述,我們將以相同的方式描述一個按寵物名稱查找所有寵物的端點。為了展示我們的目的,假設我們的系統區分大小寫,因此我們將再次為 x-constraints 驗證參數 name

/pets:
    # post defined here
    get: 
      tags: 
        - pet 
      summary: Finds Pets by name 
      description: 'Find pets by name' 
      operationId: findPetsByTags 
      parameters: 
        - name: name
          in: query 
          schema:
            type: string 
          description: Tags to filter by 
          required: true 
          x-constraints: "Capitalized(required = true)" 
      responses: 
        '200':
          description: default response
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Pet'
        '400': 
          description: Invalid tag value

4. 創建大寫標註

為了強制執行自定義驗證,我們需要創建一個標註,以確保功能的正確性。

首先,我們創建標註接口——<em @Capitalized:

@Documented
@Constraint(validatedBy = {Capitalized.class})
@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Capitalized{
    String message() default "Name should be capitalized.";
    boolean required() default true;
    // default annotation methods
}

請注意,我們為了演示目的創建了 必需 方法 – 我們稍後會解釋説明。

接下來,我們添加了 大寫驗證器 ,該驗證器在上述 @約束 註釋中引用。

public class CapitalizedValidator implements ConstraintValidator<Capitalized, String> {

    @Override
    public boolean isValid(String nameField, ConstraintValidatorContext context) {
        // validation code here
    }
}

5. 生成驗證標註

This section describes how to generate validation annotations for your code. Validation annotations are used to mark specific code sections that need to be checked for correctness and adherence to defined rules.

The process involves several steps:

  1. Define Validation Rules: First, you need to clearly define the rules that your validation annotations will enforce. These rules can cover aspects such as data types, ranges, constraints, and business logic.

  2. Identify Code Sections: Next, identify the code sections that need to be validated against these rules. This may involve static analysis, code reviews, or automated testing.

  3. Generate Annotations: Use a tool or script to automatically generate the validation annotations. These annotations typically include:

    • A unique identifier for the annotation.
    • A description of the rule being enforced.
    • The code section being validated.
  4. Apply Annotations: Apply the generated annotations to the relevant code sections. This can be done manually or automatically, depending on the tool and workflow.

  5. Verify Annotations: Verify that the annotations are correctly applied and that the code sections are being validated as expected.

Example Code Snippet with Annotation:

// This function calculates the area of a rectangle.
// It should validate that the width and height are positive numbers.
public double calculateArea(double width, double height) {
  if (width <= 0 || height <= 0) {
    // Validation annotation:  Width and height must be positive.
    throw new IllegalArgumentException("Width and height must be positive numbers.");
  }
  return width * height;
}

5.1. 指定Mustache模板目錄

為了生成帶有@Capitalized驗證註解的模型,我們需要特定的Mustache模板,告知Swagger在模型內生成它。

因此,在OpenAPI生成插件的<configuration[..]>標籤內,我們需要添加一個模板目錄:

<plugin>  
  //... 
  <executions>
    <execution>
      <configuration
        //...
        <templateDirectory>
          ${project.basedir}/src/main/resources/openapi/templates
        </templateDirectory>
        //...
      </configuration>
    </execution>
  </executions>        
  //...
</plugin> 

5.2. 添加 Mustache Bean 驗證配置

在本章中,我們將配置 Mustache 模板以生成驗證規範。為了添加更多細節,我們將修改 <em><a href="https://raw.githubusercontent.com/swagger-api/swagger-codegen/master/modules/swagger-codegen/src/main/resources/Java/beanValidationCore.mustache">beanValidationCore.mustache</a></em><em><a href="https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/main/resources/Java/model.mustache">model.mustache</a></em> 和 `api.muctache 文件,以成功生成代碼。

首先,需要修改 <em><a href="https://raw.githubusercontent.com/swagger-api/swagger-codegen/master/modules/swagger-codegen/src/main/resources/Java/beanValidationCore.mustache">beanValidationCore.mustache</a></em> 文件,即從 <em>swagger-codegen</em> 模塊中添加供應商擴展規範:

{{{ vendorExtensions.x-constraints }}}

其次,如果存在帶有內部屬性的標註,例如 @Capitalized(required = “true”),則需要在 beanValidationCore.mustache 文件第二行上指定特定的模式:

{{#required}}@Capitalized(required="{{{pattern}}}") {{/required}}

第三,我們需要修改 model.mustache 規範,使其包含必要的導入語句。例如,我們將導入 @Capitalized 註解和 Capitalized. 導入語句應插入在 package 標籤之後,位於 model.mustache: 標籤之後。

{{#imports}}import {{import}}; {{/imports}} import 
com.baeldung.openapi.petstore.validator.CapitalizedValidator; 
import com.baeldung.openapi.petstore.validator.Capitalized;

最後,要在 API 中實現標註生成,我們需要在 <em ><a href="https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/main/resources/Java/api.mustache">api.mustache</a ></em > 文件中添加對 <em >@Capitalized </em > 註解的導入。

{{#imports}}import {{import}}; {{/imports}} import 
com.baeldung.openapi.petstore.validator.Capitalized;

此外,api.mustache 依賴於 cookieParams.mustache 文件。因此,我們需要將其添加到 openapi/templates 目錄下。

6. 生成源文件

為了完成工作,我們可以使用生成的代碼。至少需要運行 mvn generate-sources 命令。這將生成模型。

public class Pet {
    @JsonProperty("id")
    private Long id = null;

    @JsonProperty("name")
    private String name = null;
    // other parameters
    @Schema(required = true, description = "")
    @Capitalized public String getName() { return name; } // default getters and setter }

它還會生成一個 API。

default ResponseEntity<List<Pet>> findPetsByTags(
    @Capitalized(required = true)
    @ApiParam(value = "Tags to filter by") 
    @Valid @RequestParam(value = "name", required = false) String name) {
    
    // default generated code here 
    return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED);
}

7. 使用 curl

啓動應用程序後,我們將使用 curl 命令進行測試。

此外,請注意,約束違例也會拋出 ConstraintViolationException。該異常需要通過 @ControllerAdvice 適當處理,以返回 400 Bad Request 狀態碼。

7.1. 驗證 Pet 模型

Pet 模型具有小寫的 name。因此,應用程序應返回 400 Bad Request 錯誤:

curl -X 'POST' \
  'http://localhost:8080/pet' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "id": 1,
  "name": "rockie"
}'

7.2. 測試 Find Pet API

正如上面所述,由於 name 為小寫,應用程序應返回 400 Bad Request 錯誤:

curl -I http://localhost:8080/pets/name="rockie"

8. 結論

在本教程中,我們學習瞭如何在實施 REST API 服務器的同時,啓用自定義約束驗證器生成的方法。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.