Reputation: 2211
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?
Upvotes: 4
Views: 6146
Reputation: 299218
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);
Upvotes: 5