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

Groovy3中List<@NotBlank String>元素级校验不生效如何解决

问题描述

使用javax.validation实现参数校验时,List<@NotBlank String>这类标注在泛型参数上的集合元素级约束,在不同语言环境下表现存在差异:

  • Java环境:可正常生效
  • Kotlin环境:添加-Xemit-jvm-type-annotations编译参数后,可正确校验集合内的每个字符串元素
  • Groovy环境:相同写法无法正常工作
复现场景

待校验实体类定义

class GroovyTestListItemValidation {

    List<@NotBlank String> inner = []

    GroovyTestListItemValidation(List<String> elements) {
        this.inner.addAll(elements)
    }

}

对应Spock测试用例

class NotBlankGroovySpec extends Specification{

    def "for each collection items with a null, blank or empty"()  {
        given: "An object to validate"
            GroovyTestListItemValidation toBe = new GroovyTestListItemValidation([null," ","","ok"])
        when: "Validation is triggered"
            Set<ConstraintViolation<?>> constraints = validate(toBe)
        then: "3 validation errors are detected"
            constraints.size() == 3
    }

    Set<ConstraintViolation<?>> validate(Object input) {
        println("Validating $input")
        Set<ConstraintViolation<?>> errs = Validation.buildDefaultValidatorFactory().validator.validate(input)
        errs.forEach {
            println("${it.propertyPath} ${it.message}")
        }
        return errs
    }

}
问题排查结论

测试预期为:向集合传入null、空白字符串、空字符串、合法字符串四个元素时,校验逻辑应检出3条违规约束,但实际测试中校验未触发。
排查编译生成的字节码发现,Groovy未将泛型类型参数上的@NotBlank注解保留在字节码中,表现和未开启类型注解输出参数的Kotlin一致。
查阅官方issue记录确认,该问题为Groovy 3.0.4版本的已知bug,已在Groovy 4版本中修复。

现存限制与诉求

当前项目受依赖版本限制无法升级到Groovy 4,同时不希望采用自定义注解的临时规避方案,希望确认是否存在类似Kotlin-Xemit-jvm-type-annotations的Groovy编译配置项,可让编译器在字节码中保留泛型类型注解,使元素级校验正常生效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 20:42:16