我正在研究基于注释的 spring 配置,并且我也想使用 Hibernate。我有一个 AnnotationSessionFactoryBean:
@Bean
public AnnotationSessionFactoryBean getSessionFactory() {
AnnotationSessionFactoryBean annotationSessionFactoryBean = new AnnotationSessionFactoryBean();
annotationSessionFactoryBean.setDataSource(getDataSource());
annotationSessionFactoryBean.setHibernateProperties(getHibernateProperties());
annotationSessionFactoryBean.setPackagesToScan("com.mobiusinversion.web");
return annotationSessionFactoryBean;
}
但是现在在我的代码中如何在 SessionFactory 中 Autowiring ,如下所示:
@Transactional
@Repository
public class UserRepository {
@Autowired
private SessionFactory sessionFactory;
}
最佳答案
AnnotationSessionFactoryBean
既是一个 InitializingBean
又是一个 FactoryBean
。这些是 Spring 作为 bean 生命周期的一部分进行处理的特殊接口(interface)。 InitializingBean
将提供 afterProperties
设置来初始化 bean,FactoryBean
将提供 getObject
用于检索 bean。然后将该 bean 添加到上下文中。
AnnotationSessionFactoryBean
生成一个 SessionFactory
bean,所以,是的,您所要做的就是 Autowiring 它
@Autowired
private SessionFactory sessionFactory;
文档中对此进行了全部解释:
您还应该阅读 javadoc。
关于java - 如何从 AnnotationSessionFactoryBean Autowiring SessionFactory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22868032/