190427-Springboot-Validated和-Valid的区别及使用

Springboot @Validated和@Valid的区别及使用

概述

  • @Valid是使用Hibernate validation的时候使用
  • @Validated是只用Spring Validator校验机制使用

java的JSR303声明了@Valid这类接口,而Hibernate-validator对其进行了实现
@Validation对@Valid进行了二次封装,在使用上并没有区别,但在分组、注解位置、嵌套验证等功能上有所不同,这里主要就这几种情况进行说明。

注解位置

@Validated:用在类型、方法和方法参数上。但不能用于成员属性(field)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* Variant of JSR-303's {@link javax.validation.Valid}, supporting the
* specification of validation groups. Designed for convenient use with
* Spring's JSR-303 support but not JSR-303 specific.
*
* <p>Can be used e.g. with Spring MVC handler methods arguments.
* Supported through {@link org.springframework.validation.SmartValidator}'s
* validation hint concept, with validation group classes acting as hint objects.
*
* <p>Can also be used with method level validation, indicating that a specific
* class is supposed to be validated at the method level (acting as a pointcut
* for the corresponding validation interceptor), but also optionally specifying
* the validation groups for method-level validation in the annotated class.
* Applying this annotation at the method level allows for overriding the
* validation groups for a specific method but does not serve as a pointcut;
* a class-level annotation is nevertheless necessary to trigger method validation
* for a specific bean to begin with. Can also be used as a meta-annotation on a
* custom stereotype annotation or a custom group-specific validated annotation.
*
* @author Juergen Hoeller
* @since 3.1
* @see javax.validation.Validator#validate(Object, Class[])
* @see org.springframework.validation.SmartValidator#validate(Object, org.springframework.validation.Errors, Object...)
* @see org.springframework.validation.beanvalidation.SpringValidatorAdapter
* @see org.springframework.validation.beanvalidation.MethodValidationPostProcessor
*/
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Validated {

/**
* Specify one or more validation groups to apply to the validation step
* kicked off by this annotation.
* <p>JSR-303 defines validation groups as custom annotations which an application declares
* for the sole purpose of using them as type-safe group arguments, as implemented in
* {@link org.springframework.validation.beanvalidation.SpringValidatorAdapter}.
* <p>Other {@link org.springframework.validation.SmartValidator} implementations may
* support class arguments in other ways as well.
*/
Class<?>[] value() default {};

@Valid:可以用在方法、构造函数、方法参数和成员属性(field)上

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Marks a property, method parameter or method return type for validation cascading.
* <p>
* Constraints defined on the object and its properties are be validated when the
* property, method parameter or method return type is validated.
* <p>
* This behavior is applied recursively.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
public @interface Valid {
}

如果@Validated注解在成员属性上,则会报 不适用于field错误

分组校验

@Validated:提供分组功能,可以在参数验证时,根据不同的分组采用不同的验证机制

@Valid:没有分组功能

下面举例说明:

  1. 定义分组接口:

    1
    2
    3
    4
    public interface IGroupA {
    }
    public interface IGroupB {
    }
  2. 定义需要检验的参数bean

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public class StudentBean implements Serializable{
    @NotBlank(message = "用户名不能为空")
    private String name;
    //只在分组为IGroupB的情况下进行验证
    @Min(value = 18, message = "年龄不能小于18岁", groups = {IGroupB.class})
    private Integer age;
    @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式错误")
    private String phoneNum;
    @Email(message = "邮箱格式错误")
    private String email;
    @MyConstraint
    private String className;
  3. 测试代码

    • 检验分组为IGroupA的情况

      1
      2
      3
      4
      5
      6
      7
      @RestController
      public class CheckController {
      @PostMapping("stu")
      public String addStu(@Validated({IGroupA.class}) @RequestBody StudentBean studentBean){
      return "add student success";
      }
      }
  4. 测试
    测试

    这里对分组IGroupB的就没检验了

    • 如果把测试代码改成下面这样,看看测试结果

      1
      2
      3
      4
      5
      6
      7
      @RestController
      public class CheckController {
      @PostMapping("stu")
      public String addStu(@Validated({IGroupA.class, IGroupB.class}) @RequestBody StudentBean studentBean){
      return "add student success";
      }
      }

      说明:
      1、不分 配groups,默认每次都要进行验证
      2、对一个参数需要多种验证方式时,也可通过分配不同的组达到目的。

组序列

默认情况下 不同级别的约束验证是无序的,但是在一些情况下,顺序验证却是很重要。

一个组可以定义为其他组的序列,使用它进行验证的时候必须符合该序列规定的顺序。在使用组序列验证的时候,如果序列前边的组验证失败,则后面的组将不再给予验证。

下面举例说明:

  1. 定义组序列

    1
    2
    3
    @GroupSequence({Default.class, IGroupA.class, IGroupB.class})
    public interface IGroup {
    }
  2. 需要校验的Bean,分别定义IGroupA对age进行校验,IGroupB对className进行校验

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class StudentBean implements Serializable{
    @NotBlank(message = "用户名不能为空")
    private String name;
    @Min(value = 18, message = "年龄不能小于18岁", groups = IGroupA.class)
    private Integer age;
    @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式错误")
    private String phoneNum;
    @Email(message = "邮箱格式错误")
    private String email;
    @MyConstraint(groups = IGroupB.class)
    private String className;
  3. 测试代码

    @RestController
    public class CheckController {

    @PostMapping("stu")
    public String addStu(@Validated({IGroup.class}) @RequestBody StudentBean studentBean){
        return "add student success";
    }

    }

  4. 测试
    测试发现,如果age出错,那么对组序列在IGroupA后的IGroupB不进行校验,即例子中的className不进行校验,结果如下:

    测试

嵌套校验

一个待验证的pojo类,其中还包含了待验证的对象,需要在待验证对象上注解@Valid,才能验证待验证对象中的成员属性,这里不能使用@Validated。

下面举例说明:

  1. 需要约束校验的bean

    1
    2
    3
    4
    5
    public class TeacherBean {
    @NotEmpty(message = "老师姓名不能为空")
    private String teacherName;
    @Min(value = 1, message = "学科类型从1开始计算")
    private int type;
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class StudentBean implements Serializable{
    @NotBlank(message = "用户名不能为空")
    private String name;
    @Min(value = 18, message = "年龄不能小于18岁")
    private Integer age;
    @Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = "手机号格式错误")
    private String phoneNum;
    @Email(message = "邮箱格式错误")
    private String email;
    @MyConstraint
    private String className;
    @NotNull(message = "任课老师不能为空")
    @Size(min = 1, message = "至少有一个老师")
    private List<TeacherBean> teacherBeans;
  2. 测试

    注意:
    这里对teacherBeans只校验了NotNull, 和 Size,并没有对teacher信息里面的字段进行校验,具体测试如下

    测试

    这里teacher中的type明显是不符合约束要求的,但是能检测通过,是因为在student中并没有做 嵌套校验

    可以在teacherBeans中加上 @Valid,具体如下:

    1
    2
    3
    4
    @Valid
    @NotNull(message = "任课老师不能为空")
    @Size(min = 1, message = "至少有一个老师")
    private List<TeacherBean> teacherBeans;

    这里再来测试,会发现如下结果:

    测试

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×