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

SpringBoot中如何验证YAML/YML文件?自动生成类场景适配

在自动生成Kotlin类的YAML中实现属性校验

针对自动生成类无法手动添加校验注解的问题,有三种可行的解决思路:

1. 用OpenAPI扩展字段+自定义代码生成模板

在YAML里给属性添加x-前缀的自定义校验标记,然后修改代码生成器的模板,让它读取这些标记并自动生成对应注解。

示例YAML:

title: Student
type: object
properties:
  id:
    type: number
    x-positive: true
    x-min: 1
  name:
    type: string
    x-not-blank: true
required:
  - name

比如用OpenAPI Generator的话,找到Kotlin模型的模板文件(如model.mustache),在属性定义部分添加逻辑:

  • 检测到x-not-blank: true时,生成@NotBlank注解
  • 检测到x-min: 1时,生成@Min(1)注解
  • 以此类推适配其他校验规则

2. 手动编写校验DTO类,继承/转换自动生成类

把自动生成的类作为基础数据类,手动创建一个带有校验注解的DTO类,业务流程中使用这个手动类,最后再转换为自动生成的类用于序列化/反序列化。

示例:
自动生成的基础类:

data class Student(
  val id: Int?,
  val name: String?
)

手动编写的校验类:

data class ValidatedStudent(
  @field:Positive
  @field:Min(1)
  val id: Int?,
  
  @field:NotBlank
  val name: String?
) {
  // 转换为自动生成的Student类
  fun toStudent() = Student(id, name)
}

这种方式不用修改代码生成逻辑,但需要维护额外的类,属性变更时要同步更新。

3. 利用代码生成器的内置校验支持

如果使用的是OpenAPI Generator这类工具,它本身支持根据OpenAPI标准约束生成JSR-380校验注解,只需开启对应配置。

首先在YAML里用标准OpenAPI约束定义规则:

title: Student
type: object
properties:
  id:
    type: integer
    minimum: 1
    exclusiveMinimum: true # 对应@Positive
  name:
    type: string
    minLength: 1 # 对应@NotBlank
required:
  - name

然后在生成代码时添加参数启用Bean Validation,比如:

openapi-generator generate -i your-spec.yaml -g kotlin -o output-dir --additional-properties=useBeanValidation=true

这样生成的Kotlin类会自动带上@Min(1)、@Positive、@NotBlank等注解,无需手动修改。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:37:13