Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSR-303 dependency injection and Hibernate

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:

@PersistenceContext
private EntityManager entityManager;

I have configured the application context with:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

Which, according to the Spring documentation, should allow “custom ConstraintValidators to benefit from dependency injection like any other Spring bean”

Within the debugger I can see Spring calling getBean to create the ConstraintValidator. Later when flush triggers the preInsert, a different ConstraintValidator is created and called. The problem is the EntityManager is null within this new ConstraintValidator. I’ve tried injecting other dependencies within the ConstraintValidator and these are always null.

Does anyone know if it is possible to inject dependencies into a ConstraintValidator?

like image 619
Jam Avatar asked Apr 26 '10 09:04

Jam


2 Answers

You can do like this if you are using Spring Boot 2.1.0+:

@Configuration
@Lazy
class SpringValidatorConfiguration {


    @Bean
    @Lazy
    public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(final Validator validator) {
        return new HibernatePropertiesCustomizer() {

            @Override
            public void customize(Map<String, Object> hibernateProperties) {
                hibernateProperties.put("javax.persistence.validation.factory", validator);
            }
        };
    }
}

The idea from Spring Boot 2.0.0 M6 - Add Hibernate Interceptor

and Spring Boot - Hibernate custom constraint doesn't inject Service

like image 126
shenyu1997 Avatar answered Nov 11 '22 06:11

shenyu1997


The best way to inject a Spring context aware ValidatorFactory inside your EntityManager is by using the javax.persistence.validation.factory property. Configuration goes as follows:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
 <property name="dataSource" ref="dataSource" />
 <property name="jpaVendorAdapter">
  <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
   <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />              
  </bean>
 </property>
 <property name="jpaPropertyMap">
  <map>
   <entry key="javax.persistence.validation.factory" value-ref="validator" />               
  </map>
 </property>
</bean>

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

Enjoy!

like image 26
Jeroen Avatar answered Nov 11 '22 07:11

Jeroen