Spring Boot参数校验注解详解

2,389 阅读1分钟
校验层
    service 层,接口、实现类都需要注解;
    controller 层;
校验位置
    参数为自定义类对象,在类属性上注解;
    其他参数,在方法参数上注解;
@Validated
    提供分组功能,根据不同分组采用不同验证机制;
    用于类、方法、方法参数上;
@Valid
    用于方法、方法参数、成员属性上,尤其在成员属性为嵌套的对象时,
    要想校验嵌套对象内属性,必须使用 @Valid 注解,且在对应(controller)
    方法参数或类上使用 @Valid 或 @Validated;
注解 作用类型 定义
@NotNull 任何 对象不能为null, 但可以是空集(size=0)
@NotEmpty 集合 对象不能为null, 且相关对象有元素(size>0)
@NotBlank 字符串、字符 String 不能为null, 且 trimAll 后的长度大于
异常
    javax.validation.ConstraintDeclarationException: HV000151: A method overriding another method must not redefine the parameter constraint configuration...
原因
    @Validated 或 @Valid 注解的类如果有继承父类或者实现接口,其父类或接口也需要注解;
参考
    https://www.cnblogs.com/javafucker/p/9935095.html
    https://www.cnblogs.com/mooba/p/11276062.html
    https://juejin.cn/post/6844904085942976519