Spring 實踐 獲取bean

2021-08-21 06:00:30 字數 1075 閱讀 2570

spring在初始化時容器會根據配置檔案初始化所有配置的bean。在使用時有兩種常用方法可以在**中獲取例項。

系統會自己根據名稱、型別去容器裡查詢對應的類並且注入,前提適用的場景必須是被spring所掃瞄到的類,且被注入到容器裡。

換句話說就是:

1、被spring掃瞄到。

2、類被註解標記。

在專案中,會遇到一些在非容器環境下還要獲取容器元件的情況,比如定時器job,在job我們會有一些資料庫操作,業務層呼叫,這時通過@autowired這種方式就會報null。這時就得讓job獲取它所在的容器

1、spring配置檔案中申明

springbeanutil"/>
2、編寫springbeanutil

import org.springframework.beans.bean***ception;

private static springbeanutil stools = null;

public synchronized static springbeanutil init()

return stools;

}throws bean***ception

public synchronized static object getbean(string beanname)

public synchronized static object getbean(class c)

}

3、**使用

sendnoticeservice sendnoticeservice = (sendnoticeservice) springbeanutil.getbean(sendnoticeservice.class);

讓Bean獲取Spring容器

實現beanfactoryaware介面的bean,擁有訪問beanfactory容器的能力,實現beanfactoryaware介面的bean例項被容器建立後,它會擁有乙個引用,該引用指向建立它的beanfactory。beanfactoryaware介面只有乙個方法 setbeanfactory...

spring獲取bean物件(六)

下面我們接著abstractbeanfactory的dogetbean中方法,如果未從快取中獲取到例項物件就會進入到下面方法 if mbd.issingleton catch bean ception ex bean getobjectforbeaninstance sharedinstance,n...

spring獲取bean的方式

import org.springframework.beans.bean ception import org.springframework.beans.factory.nosuchbeandefinitionexception import org.springframework.contex...