JSR-303 dependency injection and Hibernate

前端 未结 6 1707
长发绾君心
长发绾君心 2020-12-05 12:02

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         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 12:49

    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.

提交回复
热议问题