Spring boot, how to use @Valid with List<T>

kalahari picture kalahari · Sep 6, 2016 · Viewed 14.7k times · Source

I am trying to put validation to a Spring Boot project. So I put @NotNull annotation to Entity fields. In controller I check it like this:

@RequestMapping(value="", method = RequestMethod.POST)
public DataResponse add(@RequestBody @Valid Status status, BindingResult bindingResult) {
    if(bindingResult.hasErrors()) {
        return new DataResponse(false, bindingResult.toString());
    }

    statusService.add(status);

    return  new DataResponse(true, "");
}

This works. But when I make it with input List<Status> statuses, it doesn't work.

@RequestMapping(value="/bulk", method = RequestMethod.POST)
public List<DataResponse> bulkAdd(@RequestBody @Valid List<Status> statuses, BindingResult bindingResult) {
    // some code here
}

Basically, what I want is to apply validation check like in the add method to each Status object in the requestbody list. So, the sender will now which objects have fault and which has not.

How can I do this in a simple, fast way?

Answer

ameenhere picture ameenhere · Sep 6, 2016

My immediate suggestion is to wrap the List in another POJO bean. And use that as the request body parameter.

In your example.

@RequestMapping(value="/bulk", method = RequestMethod.POST)
public List<DataResponse> bulkAdd(@RequestBody @Valid StatusList statusList, BindingResult bindingResult) {
// some code here
}

and StatusList.java will be

@Valid
private List<Status> statuses;
//Getter //Setter //Constructors

I did not try it though.

Update: The accepted answer in this SO link gives a good explanation why bean validation are not supported on Lists.