JSR-303 dependency injection and Hibernate

前端 未结 6 1708
长发绾君心
长发绾君心 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:58

    It seems that in JPA2, the persistence provider's validation mechanism kicks in by default on pre-persist, pre-update, etc.

    It uses its own mechanism for constructing validators, Spring doesn't get involved.

    The only solution I can see at the moment is disabling the out-of-the-box JPA2 validation in persistence.xml:

    
      org.hibernate.ejb.HibernatePersistence
        
          
          
        
      NONE
    
    

    Then use Spring's LocalValidatiorFactoryBean as usual. You'll then have to call the validators manually as in the pre-JPA2 world.

    UPDATE:

    Just to make it complete, another solution would be to specify a constraint-validator-factory in META-INF/validation.xml.

    It would be very nice if this could be Spring's SpringConstraintValidatorFactory but unfortunately, it requires an AutowireCapableBeanFactory to be passed into its constructor, but a class with no-arg constructor is expected here by JPA2.

    Which leaves the option of creating own implementation of ConstraintValidatorFactory that pulls validators out of Spring, but I don't see any clean way of doing that.

提交回复
热议问题