学习Spring的过程中,一直不理解为何需要用LocalSessionFactoryBean来得到SessionFactory,LocalSessionFactoryBean 本身不是一个session factory,但是spring会自动把对这个bean的引用替换成LocalSessionFactoryBean 里面的真正的session factory。
Hibernate提供的SessionFactory接口的实现类SessionFactoryImpl没有注入数据源的setter方法(上面的代码是直接把hibernate配置文件注入给了LocalSessionFactoryBean,也可以把一个数据源dataSource注入给它)所以为了完成spring的依赖注入,Spring提供了LocalSessionFactoryBean这个类.
现在我们有个这样的问题:
我们想要一个org.hibernate.SessionFactory类.而我们在Spring容器中确是一个LocalSessionFactoryBean类。
publicclass LocalSessionFactoryBean implements FactoryBean, InitializingBean, DisposableBean {
private SessionFactory sessionFactory;
public Object getObject(); {
returnthis.sessionFactory;
}
当引用这个LocalSessionFactoryBean 的时候,比如applicationContext.getBean("localSessionFactoryBean ")这样,spring返回的不是LocalSessionFactoryBean 本身,他会自动调用getObject()这个方法,把真正的session factory返回。用<ref bean="">这样引用也一样,得到的都是session factory而不是LocalSessionFactoryBean 。这里代码没贴全,有兴趣的话去看看源代码。 所以不需要再显式地创建一个session factory,直接引用LocalSessionFactoryBean 就可以了。
2.
LocalSessionFactoryBean实现了org.springframework.beans.factory.FactoryBean接 口, spring在装配的时候, 如果发现实现了org.springframework.beans.factory.FactoryBean接口, 就会使用FactoryBean#getObject() 方法返回的对象装配,具体的可以看下文档.
如果你想拿到LocalSessionFactoryBean实例, 在id前面加个'&'就可以了,在你的配置文件中BeanFactory.getBean('&sessionFactory')拿到的 就是LocalSessionFactoryBean的实例.