2011-03-06 132 views
4

我需要創建一個必須有權訪問實體管理器的Hibernate攔截器。問題是當我定義如何使用Spring中的XML配置文件創建EntityManagerFactory來定義entityManagerFactory bean時,我必須告訴實體管理它必須使用哪個攔截器bean。問題是,我的攔截豆已經使用如何使用Spring在Hibernate攔截器Bean中注入EntityManager?

@PersistenceContext private EntityManager entityManager; 

注入實體管理領域的定義。當我做這個春天拋出以下異常:

產生的原因:org.springframework.beans.factory.BeanCreationException :在類路徑資源[ar/com/xxx/impl/config/persistence/persistence-impl-xxx-spring.xml中定義的名稱'ar.com.zauber.commons.repository.utils.ConfigurableHibernatePersistence#50d17ec3'中創建bean時出錯]:設置bean屬性'攔截器'時,無法解析對bean'攔截器'的引用;嵌套異常是org.springframework.beans.factory.BeanCreationException:使用名稱'攔截器'創建bean時出錯:持久性依賴關係的注入失敗;嵌套的例外是org.springframework.beans.factory.BeanCurrentlyInCreationException:錯誤創建名稱爲豆「的entityManagerFactory」:的FactoryBean這是目前在創作返回null從的getObject

的問題是,實體管理器不能因爲注入實體經理工廠正在創建中。

任何想法我該如何解決這個問題?

回答

3

使用取決於上(XML版本):

<bean id="interceptor" 
    class="YourHibernateInterceptor" depends-on="entityManagerFactory"/> 

或者@DependsOn(譯註版):

@DependsOn("entityManagerFactory") 
public class YourHibernateInterceptor{ 
    // ... 
} 

參考:


如果這不起作用,因爲它是一個雞/蛋的問題(EntityManagerFactory的依賴於SessionFactory的,SessionListener取決於EntityManagerFactory的,你可以標記您SessionListener因爲無論是ApplicationContextAwareApplicationListener<ContextRefreshedEvent>和手動接線EntityManager

this.entityManager = context.getBean(EntityManager.class);