簡體   English   中英

如何實例化通用Spring bean?

[英]How to instantiate generic spring bean?

我正在嘗試創建一個通用類,該類將幫助我減少樣板代碼。 我為此使用Spring 3(MVC)和Hibernate 4。

類看起來像這樣:

@Repository("AutoComplete")
public class AutoComplete<T extends Serializable> implements IAutoComplete {

    @Autowired
    private SessionFactory sessionFactory;

    private Class<T> entity;

    public AutoComplete(Class<T> entity) {
        this.setEntity(entity);
    }

    @Transactional(readOnly=true)
    public List<String> getAllFTS(String searchTerm) {
        Session session = sessionFactory.getCurrentSession();
        return null;
    }

    public Class<T> getEntity() {
        return entity;
    }

    public void setEntity(Class<T> entity) {
        this.entity = entity;
    }

}

我像這樣實例化bean:

IAutoComplete place = new AutoComplete<Place>(Place.class);
place.getAllFTS("something");

如果我運行代碼,則會收到“未找到默認構造函數”異常。 如果添加默認構造函數,則在此行將得到空指針異常:

Session session = sessionFactory.getCurrentSession();

為什么會這樣,我該如何解決呢? 我猜問題是因為Spring本身沒有實例化bean,所以它不能自動裝配字段。 我想自己實例化bean,但如果可能的話,仍要在春季進行管理。

確保在xml bean定義文件中添加了<context:component-scan base-package='package name'>

由於@Repository是構造型,因此Spring容器將進行類路徑掃描,添加其bean定義並注入其依賴項。

稍后,您可以從ApplicationContext使用bean名稱(AutoComplete)獲得bean的句柄。

Spring容器將為您實例化此bean,在這種情況下,將注入sessionFactory。 您可以通過自己的代碼實例化此bean:new AutoComplete(),當然sessionFactory為null。

切勿使用帶有@Autowired批注的字段實例化類。 如果這樣做,該字段將為空。 您應該做的是應該獲得對Spring的ApplicationContext的引用(可以通過實現ApplicationContextAware接口來實現此目的),並在AutoComplete類的默認構造函數中使用以下代碼。

public AutoComplete() {
    sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
}

使用Spring的主要實踐之一是自己消除對象的實例化。 我們應該在spring配置中指定所有內容,以便Spring在需要時為我們實例化對象。 但是,對於通用方法,您需要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM