簡體   English   中英

如何使用Spring在Hibernate Interceptor Bean中注入EntityManager?

[英]How to Inject the EntityManager in an Hibernate Interceptor Bean using Spring?

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

@PersistenceContext private EntityManager entityManager;

當我這樣做時,Spring拋出以下異常:

引起:org.springframework.beans.factory.BeanCreationException:創建名為'ar.com.zauber.commons.repository.utils.ConfigurableHibernatePersistence#50d17ec3'的bean在類路徑資源中定義時出錯[ar / com / xxx / impl / config /persistence/persistence-impl-xxx-spring.xml]:設置bean屬性'interceptor'時無法解析對bean'interceptor'的引用; 嵌套異常是org.springframework.beans.factory.BeanCreationException:創建名為'interceptor'的bean時出錯:持久性依賴項的注入失敗; 嵌套異常是org.springframework.beans.factory.BeanCurrentlyInCreationException:創建名為'entityManagerFactory'的bean時出錯:當前處於創建狀態的FactoryBean從getObject返回null

問題是無法注入實體管理器,因為正在創建實體管理器工廠。

不知道怎樣才能解決這個問題?

使用依賴(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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM