【问题标题】:How to Autowire SessionFactory from AnnotationSessionFactoryBean如何从 AnnotationSessionFactoryBean 自动装配 SessionFactory
【发布时间】:2014-04-04 16:20:55
【问题描述】:

我正在开发基于注解的 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 中自动装配,如下所示:

@Transactional
@Repository
public class UserRepository {

    @Autowired
    private SessionFactory sessionFactory;

}

【问题讨论】:

  • 这应该行吗?我不认为 Spring 会理解如何使用 AnnotationSessionFactoryBean 注入 SessionFactory

标签: java spring hibernate annotations


【解决方案1】:

AnnotationSessionFactoryBean 既是 InitializingBean 又是 FactoryBean。这些是 Spring 在 bean 生命周期中处理的特殊接口。 InitializingBean 将提供 afterProperties 设置来初始化 bean,FactoryBean 将提供 getObject 用于检索 bean。然后将该 bean 添加到上下文中。

AnnotationSessionFactoryBean 产生一个SessionFactory bean,所以,是的,你所要做的就是自动装配它

@Autowired
private SessionFactory sessionFactory;

这在文档中都有解释:

您还应该阅读 javadoc。

【讨论】:

  • 知道了,谢谢。非常感谢您对它的工作原理进行了清晰而详细的解释,我仍在学习 Spring,这非常有帮助。
猜你喜欢
  • 1970-01-01
  • 2016-06-06
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 2018-12-27
  • 1970-01-01
相关资源
最近更新 更多