Java/Spring: Why won't Spring use the validator object I have configured?

Posted by GMK on Stack Overflow See other posts from Stack Overflow or by GMK
Published on 2010-03-25T17:13:16Z Indexed on 2010/03/25 17:33 UTC
Read the original article Hit count: 485

Filed under:
|
|
|

I'm writing a web app with Java & Spring 2.5.6 and using annotations for bean validation. I can get the basic annotation validation working fine, and Spring will even call a custom Validator declared with @Validator on the target bean. But it always instantiates a brand new Validator object to do it. This is bad because the new validator has none of the injected dependencies it needs to run, and so it throws a null pointer exception on validate. I need one of two things and I don't know how to do either.

  1. Convince Spring to use the validator I have already configured.
  2. Convince Spring to honor the @Autowired annotations when it creates the new validator.

The validator has the @Component annotation, like this.

@Component
public class AccessCodeBeanValidator implements Validator {
    @Autowired
    private MessageSource messageSource;

Spring finds the validator in the component scan, injects the autowired dependencies, but then ignores it and creates a new one at validation time.

The only thing that I can do at the moment is add a validator reference into the controller for each validator object and use that ref directly, instead of relying on the bean validation framework to call the validator for me. It looks like this.

// first validate via the annotations on the bean
beanValidator.validate(accessCodeBean, result);
// then validate using the specific validator class
acbValidator.validate(accessCodeBean, result);
if (result.hasErrors()) {

If anyone knows how to convince spring to use the existing validator, instead of creating a new one, or how to make it do the autowiring when it creates a new one, I'd love to know.

© Stack Overflow or respective owner

Related posts about java

Related posts about spring