Validating a List of beans using Bean Validation 2.0 (JSR-308) and Spring 5

半腔热情 提交于 2019-12-08 11:24:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!