有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从AnnotationSessionFactoryBean自动连接SessionFactory

我正在开发一个基于注释的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;

}

共 (1) 个答案

  1. # 1 楼答案

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

    AnnotationSessionFactoryBean产生一个SessionFactorybean,所以,是的,然后你需要做的就是自动连接它

    @Autowired
    private SessionFactory sessionFactory;
    

    这些都在文档中进行了解释:

    您还应该浏览javadoc