You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenAPI 3.0.1中指定数组元素非空且满足长度要求?

解决OpenAPI Schema生成Java代码时数组元素的非空与长度校验问题

问题背景

基于Java 17和Spring Boot项目,使用SpringDoc根据OpenAPI 3.0.1规范生成Java代码。当前定义的Schema如下:

components:
  schemas:
    cardKey:
      description: ...
      format: base64
      type: string
    
    newRequest:
      description: ...
      properties:
        cardKeyList:
          description: ...
          items:
            $ref: '#/components/schemas/cardKey'
          minItems: 1
          type: array
      required:
      - cards # 注:此处存在笔误,应为cardKeyList

生成的Java代码为:

@Valid
private List<String> cardKeyList = new ArrayList<>();

需要实现cardKeyList中的每个cardKey元素不能为null且字符串最小长度至少为1,但找不到对应配置方式。

解决方案

1. 修正并完善OpenAPI Schema定义

要让生成的代码带上元素级别的校验约束,需先在Schema中明确声明这些规则:

components:
  schemas:
    cardKey:
      description: ...
      format: base64
      type: string
      minLength: 1  # 指定字符串最小长度为1
      nullable: false  # 禁止元素为null
    
    newRequest:
      description: ...
      properties:
        cardKeyList:
          description: ...
          items:
            $ref: '#/components/schemas/cardKey'
          minItems: 1
          type: array
          nullable: false  # 若整个数组不能为null可添加此配置
      required:
      - cardKeyList  # 修正原笔误,确保字段名匹配

2. 启用SpringDoc的Bean Validation生成

在项目配置文件(如application.yml)中添加以下配置,让SpringDoc自动生成JSR-380校验注解:

springdoc:
  codegen:
    bean-validation-enabled: true

3. 验证生成结果

配置完成后重新生成Java代码,cardKeyList字段会带上元素级别的校验注解,示例如下:

@Valid
@NotNull
@Size(min = 1)
private List<@NotNull @NotBlank @Pattern(regexp = "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$") String> cardKeyList = new ArrayList<>();

其中:

  • @NotNull 确保列表元素不为null
  • @NotBlank 确保字符串非空且长度≥1(等价于@NotNull + @Size(min=1))
  • @Pattern 对应base64格式的正则校验

内容的提问来源于stack exchange,提问作者Eugene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 11:54:05