1

I have added <mvc:annotation-driven/> to my Spring configuration, and according to the documentation it will provide:

Support for validating @Controller inputs with @Valid, if a JSR-303 Provider is present on the classpath. The validation system can be explicitly configured by setting the validator attribute.

From this and other documents, I have taken it to mean that I no longer need to explicitly inject a validator within my controller classes and it will be done automatically. Is this correct?

Currently I need to have the following in my controller:

@Autowired
private Validator validator;

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.setValidator(validator);
}

Can anyone clear this up for me? Thanks

Steve
  • 2,207
  • 6
  • 24
  • 35

1 Answers1

1

Yes, it's correct. With <mvc:annotation-driven> you don't need to inject validator explicitly.

Note that in a typical Spring MVC application you have two application contexts, see here for more details, and <mvc:annotation-driven> must be declared in the DispatcherServlet's context.

Community
  • 1
  • 1
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • But I do have to inject it explicitly, or else the validation doesn't work. What could I be missing? – Steve Nov 26 '10 at 16:19
  • 1
    @Steve: Make sure that `` is declared in `DispatcherServlet`'s context, i.e. `...-servlet.xml`. – axtavt Nov 26 '10 at 16:24
  • I usually declare things in `myapp-config.xml`, which is referenced as a `contextConfigLocation` in my `web.xml`. This is because I found that `myapp-servlet.xml` would be executed twice, once by Tomcat and then again by Spring. Breakpoints show that `AnnotationDrivenBeanDefinitionParser` is being executed – Steve Nov 26 '10 at 16:47
  • @Steve: Updated. To avoid double execution you shouldn't add `myapp-servlet.xml` to `contextConfigLocation`. – axtavt Nov 26 '10 at 17:07
  • Is it normal to require mvc:annotation-driven in both application contexts? I seem to need it in myapp-config.xml to have the @Controllers work – Steve Nov 26 '10 at 17:56
  • @Steve: The typical approach is to have `` in `myapp-servlet.xml` as well as controllers. – axtavt Nov 26 '10 at 18:03