问题描述
Spring 3.0.2,休眠 3.5.0,休眠验证器 4.0.2.GA
Spring 3.0.2,Hibernate 3.5.0,Hibernate-Validator 4.0.2.GA
我正在尝试使用以下方法将 Spring 依赖项注入 ConstraintValidator:
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"/>
根据 Spring 文档,这应该允许自定义 ConstraintValidators 像任何其他 Spring bean 一样从依赖注入中受益"
Which, according to the Spring documentation, should allow "custom ConstraintValidators to benefit from dependency injection like any other Spring bean"
在调试器中,我可以看到 Spring 调用 getBean 来创建 ConstraintValidator.稍后,当刷新触发 preInsert 时,会创建并调用不同的 ConstraintValidator.问题是 EntityManager 在这个新的 ConstraintValidator 中为空.我尝试在 ConstraintValidator 中注入其他依赖项,但这些依赖项始终为空.
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.
有谁知道是否可以将依赖项注入到 ConstraintValidator 中?
Does anyone know if it is possible to inject dependencies into a ConstraintValidator?
推荐答案
在 EntityManager 中注入 Spring 上下文感知 ValidatorFactory 的最佳方法是使用 javax.persistence.validation.factory 属性.配置如下:
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"/>
享受吧!
这篇关于JSR-303 依赖注入和 Hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!