歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 淺析Spring之sessionFactory

淺析Spring之sessionFactory

日期:2017/3/1 10:18:15   编辑:Linux編程

我們知道當我們集成Hibernate,我們需要Spring管理事務,自然而然就需要SessionFactory來創建Session,但是我們發現在Spring依賴注入的並不是SessionFactory,而是org.springframework.orm.hibernate3.LocalSessionFactoryBean

通過LocalSessionFactoryBean源碼發現LocalSessionFactoryBean extends AbstractSessionFactoryBean,而AbstractSessionFactoryBean implements FactoryBean<SessionFactory>的一個接口

public interface FactoryBean<T> {

T getObject() throws Exception;

Class<?> getObjectType();

boolean isSingleton();

}

LocalSessionFactoryBean 並不是真正的SessionFactory,只是擁有創建SessionFactory的能力,但Spring會自動把對這個Bean的引用轉換成LocalSessionFactoryBean裡面的SessionFactory。所以當Spring加載時,如果發現某個bean實現了FactoryBean接口,就會自動調用FactoryBean.getObject(),返回對應的實例。所以使用ctx.getBean("sessionFactory");Spring返回的不是LocalSessionFactoryBean本身,而是返回具體的<T>

總結:通過Spring的這個特性我們也可以編寫類似於這種模式功能,只要實現FactoryBean<SessionFactory>接口,接下來就可以通過Spring返回你想返回的對象了。

Copyright © Linux教程網 All Rights Reserved