Validation of a list of objects in Spring

I found another approach that works. The basic problem is that you want to have a list as your input payload for your service, but javax.validation won’t validate a list, only a JavaBean. The trick is to use a custom list class that functions as both a List and a JavaBean:

@RequestBody @Valid List<CompanyTag> categories

Change to:

@RequestBody @Valid ValidList<CompanyTag> categories

Your list subclass would look something like this:

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 ...
}

Leave a Comment