简体   繁体   中英

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

I need to create an Hibernate interceptor that must have access to the entity manager. The problem is that when I am defining how the EntityManagerFactory is going to be created using the XML config file in Spring for defining the entityManagerFactory bean I have to tell the entity manage which interceptor bean it must use. The thing is that my Interceptor bean has an injected entity manager field defined using

@PersistenceContext private EntityManager entityManager;

When I do this Spring throws the following exception:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ar.com.zauber.commons.repository.utils.ConfigurableHibernatePersistence#50d17ec3' defined in class path resource [ar/com/xxx/impl/config/persistence/persistence-impl-xxx-spring.xml]: Cannot resolve reference to bean 'interceptor' while setting bean property 'interceptor'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'interceptor': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'entityManagerFactory': FactoryBean which is currently in creation returned null from getObject

The problem is that the entity manager could not be injected because the entity manager factory is being created.

Any idea how can I solve this problem?

Use depends-on (XML version):

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

Or @DependsOn (Annotation version):

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

Reference:


If this doesn't work because it's a chicken / egg problem (EntityManagerFactory depends on SessionFactory, SessionListener depends on EntityManagerFactory, you can mark your SessionListener as either ApplicationContextAware or ApplicationListener<ContextRefreshedEvent> and manually wire the EntityManager :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM