I have a simple class Foo, saying like this one :
Now, I have a controller REST method that take an array (or collection) of Foos where I want to ensure every Foo has a non-null bar property. I thought using the @Valid annotation would make the trick, but it seems it isn't :Code:public class Foo { @NotNull private String bar; public String getBar(){ return bar; } public void setBar(String _bar){ this.bar = _bar; } }
Note: It doesn't work with a List<Foo> either. But with a unique Foo it works !Code:@Controller public class MyController { @RequestMapping(value="/foos", method=RequestMethod.POST) public @ResponseBody String createFoos(@Valid @RequestBody Foo[] foos){ // blah blah blah return "yeah"; } }
Looks like Spring validation doesn't work when we have "multiple" root objects (in collection or array) ... even if we use @Valid on it in controller's methods.
I even tried to implement a HandlerMethodArgumentResolver with a custom annotation, but I don't know how to define "indexed property names" in BindingResult.
The only workaround I found is to wrap my collection in an entity like this :
And use it in my controller :Code:public class UselessFooContainer { @Valid @NotEmpty Foo[] foos; public Foo[] getFoos(){ return foos; } public void setFoos(Foo[] foos){ this.foos = foos; } }
If someone knows a better workaround for this problem, it is welcome !Code:@Controller public class MyController { @RequestMapping(value="/foos", method=RequestMethod.POST) public @ResponseBody String createFoos(@Valid @RequestBody UselessFooContainer foosContainer){ // blah blah blah return "yeah"; } }![]()


Reply With Quote
