Spring 3, JSR-303 validation (bean) and collection validation

I have a simple Foo class saying like this:

public class Foo { @NotNull private String bar; public String getBar(){ return bar; } public void setBar(String _bar){ this.bar = _bar; } } 

Now I have a REST controller method that accepts an Foos array (or collection), where I want each Foo to have a non-empty bar property. I thought using the @Valid annotation would do the trick, but it doesn't seem to be that way:

 @Controller public class MyController { @RequestMapping(value="/foos", method=RequestMethod.POST) public @ResponseBody String createFoos(@Valid @RequestBody Foo[] foos){ // blah blah blah return "yeah"; } } 

Note. This does not work with the <Foo> or list. But with unique Foo, it works!

It seems that Spring validation does not work when we have "several" objects (in a collection or an array).

I even tried to implement HandlerMethodArgumentResolver with 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 quite helpful! :)

+4
source share
1 answer

Here are a few things that I think you missed in your implementation. You want to use the concept of object graphics to make this work.

Your Foo class has an @NotNull check in one of its fields, however you really haven't expressed what should be valid with the collection.

From Hibernate Help:

Validation of an object graph also works for fields into which a set is entered. This means that any attributes that are arrays implement java.lang.Iterable (especially Collection, List and Set) or implement java.util.Map can be annotated using @Valid, which will result in checking each contained element when the parent object will be checked.

So your code will 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"; } } 
0
source

Source: https://habr.com/ru/post/1390546/


All Articles