【发布时间】:2014-08-16 19:05:28
【问题描述】:
在 Spring Boot 应用程序中,我试图从自定义 BeanPostProcessor 中获取 HibernateEntityManagerFactory,例如:
public class HibernateEventListenerBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
private ApplicationContext applicationContext;
private HibernateEntityManagerFactory entityManagerFactory;
private EventListenerRegistry eventListenerRegistry;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// TODO do the stuff with beans of various types
return bean;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
this.entityManagerFactory = applicationContext.getBean(HibernateEntityManagerFactory.class);
}
}
但它给了我:
Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.jpa.HibernateEntityManagerFactory] is defined
当我尝试在普通 bean 中自动装配 HibernteEntityManagerFactory 时,它可以正常工作。例如:
@Component
public class HibernateEventListenerRegistrar {
private HibernateEntityManagerFactory entityManagerFactory;
@Autowired
public HibernateEventListenerRegistrar(HibernateEntityManagerFactory entityManagerFactory, List<HibernateEventListener> hibernateEventListeners) {
this.entityManagerFactory = entityManagerFactory;
}
@PostConstruct
public void registerListeners() {
// TODO
}
}
是否可以在 Spring BeanPostProcessor 中访问 HibernateEntityManagerFactory?
【问题讨论】:
-
如果this 有任何帮助。
-
感谢您的链接,但我不知道它有什么帮助...如果您不这么认为,请告诉我
-
为什么不把 HibernateEventListenerRegistrar 变成 @Configuration 类而不是 @Component?无需处理 bean 后处理器
-
@geoand 那应该如何工作?我需要用各种类型的豆子做一些事情。这就是为什么我在考虑一个 BeanPostProcessor。同样重要的是,他们要了解订单。
-
看你的代码,我以为你需要做的事情被
HibernateEventListenerRegistrar总结了。由于它是 Spring 配置的一部分,因此您应该使用@Configuration而不是@Component
标签: spring hibernate spring-boot