Announcement Announcement Module
Collapse
No announcement yet.
JSR-303 (bean validation) and validating collection Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • JSR-303 (bean validation) and validating collection

    I have a simple class Foo, saying like this one :

    Code:
    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 :

    Code:
    @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" 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 :
    Code:
    public class UselessFooContainer {
        @Valid @NotEmpty
        Foo[] foos;
        public Foo[] getFoos(){ return foos; }
        public void setFoos(Foo[] foos){ this.foos = foos; }
    }
    And use it in my controller :
    Code:
    @Controller
    public class MyController {
        @RequestMapping(value="/foos", method=RequestMethod.POST)
        public @ResponseBody String createFoos(@Valid @RequestBody UselessFooContainer foosContainer){
            // blah blah blah
            return "yeah";
        }
    }
    If someone knows a better workaround for this problem, it is welcome !
    Last edited by Atma; Feb 10th, 2012, 02:09 AM.

  • #2
    Wrapping the array or collection in a containing bean like you have done is a common way to make binding and validation work. I use this technique frequently. In real-world cases, it is not uncommon to find that it is useful to have the containing bean anyway so you can manipulate the collection, implement finder methods, etc. without breaking encapsulation.

    Comment

    Working...
    X