Java – Validation of a list of objects in Spring

javalistspringvalidation

I have the following controller method:

@RequestMapping(value="/map/update", method=RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseEntityWrapper updateMapTheme(
        HttpServletRequest request, 
        @RequestBody @Valid List<CompanyTag> categories,
        HttpServletResponse response
        ) throws ResourceNotFoundException, AuthorizationException {
...
}

CompanyTag is defined this way:

public class CompanyTag {
    @StringUUIDValidation String key;
    String value;
    String color;
    String icon;
    Icon iconObj;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
   ...
}

The problem is that validation is not triggered, the CompanyTag list is not validated, the "StringUUIDValidation" validator is never called.

If I remove the List and only try to send a single CompanyTag, i.e. instead of:

@RequestBody @Valid List<CompanyTag> categories,

use:

@RequestBody @Valid CompanyTag category,

it works as expected, so apparently Spring does not like to validate lists of things (tried with array instead, that did not work either).

Anybody have any idea what's missing?

Best Answer

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