问题
Spring 5 is supposed to support Bean Validation 2.0 which introduced validation on List types but I can't seem to get it to work for me.
I have the following endpoint in my @RestController
:
@PostMapping("/foos")
public List<Foo> analysePoints(@RequestBody @Valid List<@Valid Foo> request) {
...
}
Where the class Foo has some JSR validation annotations on its properties.
Unfortunately, this doesn't seem to validate it at all. Prior to Spring 5 I got around this by wrapping the List<Foo>
in a separate request bean object and this does work in this case too but I don't want to have to do this because it changes the format of the json required.
Is there any way to get this working?
回答1:
javax.validation
won't validate a list, only a JavaBean. The workaround is to use a customized List class:
Instead of
@RequestBody @Valid List<@Valid Foo> request
Use:
@RequestBody @Valid ValidList<@Valid Foo> request
ValidList
public class ValidList<E> implements List<E> {
@Valid
private List<E> list;
public ValidList() {
this.list = new ArrayList<E>();
}
public ValidList(List<E> list) {
this.list = list;
}
// Bean-like methods, used by javax.validation but ignored by JSON parsing
public List<E> getList() {
return list;
}
public void setList(List<E> list) {
this.list = list;
}
// List-like methods, used by JSON parsing but ignored by javax.validation
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
// Other list methods ...
}
来源:https://stackoverflow.com/questions/52314038/validating-a-list-of-beans-using-bean-validation-2-0-jsr-308-and-spring-5