Spring validates the nesting of validation parameters

Time:2020-9-19

Comments involved: @ validated and @ valid


To class used:

Class A

public class A {

    @NotEmpty(message="name can't be empty")
    private String name;
    
    @NotEmpty(message="id can't be empty")
    private Long id;
}

Class B

public class B {
    
    @NotEmpty(message = "aList can't be empty")
    private List<@Valid A> aList;
}

Class C

public class C {
    
    @NotNull(message = "a can't be empty")
    @Valid
    private A a;
}

1、 The parameter is directly a list

(1) . first add the annotation @ validated at the top of the controller
    @Validated
    @RestController
    @RequestMapping("/xxx/")
    public class XXXController {}
(2) . add the @ valid annotation to the corresponding list parameter defined by the controller interface
    @PostMapping("yyy")
    public Result<Void> testValidator(@Valid @RequestBody List<A> params){}

2、 The parameter is an object, and a list is nested in the object

(1) . first add the annotation @ validated at the top of the controller
    @Validated
    @RestController
    @RequestMapping("/xxx/")
    public class XXXController {}
(2) . add the @ validated annotation and @ valid annotation in the corresponding parameters defined by the controller interface (because @ valid can play the role of nested verification)
    @PostMapping("yyy")
    public Result<Void> testValidator(@Valid @Validated @RequestBody B b){}
(3) . add the @ valid annotation to the list attribute of the entity
@NotEmpty(message = "aList can't be empty")
    private List<@Valid A> aList;
    //Or
    @NotEmpty(message = "aList can't be empty")
    @Valid 
    private List<A> aList;

3、 Parameters are objects, objects are nested within objects

(1) . first add the annotation @ validated at the top of the controller
    @Validated
    @RestController
    @RequestMapping("/xxx/")
    public class XXXController {}
(2) . add the @ validated annotation and @ valid annotation in the corresponding parameters defined by the controller interface (because @ valid can play the role of nested verification)
    @PostMapping("yyy")
    public Result<Void> testValidator(@Valid @Validated @RequestBody C c){}
(3) . add @ valid annotation to the object attribute of entity
    @NotNull(message = "a can't be empty")
    @Valid
    private A a;
    

Tip: @ valid does not conflict with the grouping function of @ validated. The group attribute collection is used normally