Spring 3.0.2, Hibernate 3.5.0, Hibernate-Validator 4.0.2.GA
I am trying to inject Spring dependencies into a ConstraintValidator using:
@PersistenceC
Although JSR-303 (Hibernate Validator being the reference implementation) instantiates our custom ConstraintValidator, it in effect delegates the actual creation to a ValidatorFactory. So you are right to think that using Spring's LocalValidatorFactoryBean should enable dependency injection for your custom validators throughout your application.
The subtlety here lies in the fact that Hibernate itself uses a separate ValidatorFactory than the one configured in your Spring context when handling entity lifecycle events (pre-update, pre-insert, pre-delete). This is by design I think: Hibernate Validator is not aware of Spring, so we must tell Hibernate to use Spring's LocalValidatorFactoryBean instead of creating its own.
Basically, something like this is required in your Spring application context XML:
...
Since I've struggled for a while to find out how to do it, I've put together a demo app here on Github The README file is self-explanatory.