I have a simple class Foo, saying like this one :
public class Foo {
@NotNull
private String bar;
public String getBar(){ return bar; }
public void setBar(String _bar){ this.bar = _bar; }
}
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 :
@Controller
public class MyController {
@RequestMapping(value="/foos", method=RequestMethod.POST)
public @ResponseBody String createFoos(@Valid @RequestBody Foo[] foos){
// blah blah blah
return "yeah";
}
}
Note: It doesn't work with a List<Foo> either. But with a unique Foo it works !
Looks like Spring validation doesn't work when we have "multiple" objects (in collection or array).
I even tried to implement a HandlerMethodArgumentResolver with a custom annotation, but I don't know how to define "indexed property names" in BindingResult.
If someone knows a workaround for this problem, it would be greatly appreciated ! :)
There's a few things I think you've missed in your implementation. You'll want to use the notion of object graphs to make this work.
Your class Foo has the @NotNull validation on one of its fields, however you haven't really expressed what needs to be valid with the collection.
From the Hibernate Reference:
Object graph validation also works for collection-typed fields. That means any attributes that are arrays, implement java.lang.Iterable (especially Collection, List and Set) or implement java.util.Map can be annotated with @Valid, which will cause each contained element to be validated, when the parent object is validated.
So your code would become
@Controller
public class MyController {
@RequestMapping(value="/foos", method=RequestMethod.POST)
public @ResponseBody String createFoos(@Valid @NotNull @RequestBody Foo[] foos){
// blah blah blah
return "yeah";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.