當通過xml檔案載入所有的bean到ioc容器裡面後,可以通過getbean方法來獲取所需要的類的實類
public
public
static
void
main(string args)
}
public object getbean(string name) throws bean***ception
public
t getbean(string name, @nullable classrequiredtype) throws bean***ception
public object getbean(string name, object... args) throws bean***ception
他會根據傳進來的不同的引數來判斷具體呼叫哪個方法,在方法裡面的this.assertbeanfactoryactive();用來判斷是否已經存在。接著會呼叫abstractbeanfactory裡面的getbean 方法
public
t getbean(string name, @nullable classrequiredtype) throws bean***ception
public object getbean(string name, object... args) throws bean***ception
public
t getbean(string name, @nullable classrequiredtype, @nullable object... args) throws bean***ception
同樣在通過傳進來的引數來呼叫相應的方法,在該方法裡面dogetbean 方法,
protected t dogetbean(string name, @nullable classrequiredtype, @nullable object args, boolean typecheckonly) throws bean***ception else
}bean = this.getobjectforbeaninstance(sharedinstance, name, beanname, (rootbeandefinition)null);
} else
beanfactory parentbeanfactory = this.getparentbeanfactory();
if (parentbeanfactory != null && !this.containsbeandefinition(beanname))
if (args != null)
return parentbeanfactory.getbean(nametolookup, requiredtype);
}if (!typecheckonly)
try
this.registerdependentbean(dep, beanname);
try catch (nosuchbeandefinitionexception var24) }}
if (mbd.issingleton()) catch (bean***ception var5)
});bean = this.getobjectforbeaninstance
(sharedinstance, name, beanname, mbd);
} else
if(mbd.isprototype()) finally
bean = this.getobjectforbeaninstance
(prototypeinstance, name, beanname, mbd);
} else
try finally
return var4;
});bean = this.getobjectforbeaninstance
(scopedinstance, name, beanname, mbd);
} catch
(illegalstateexception var23)
}} catch
(bean***ception var26) }if
(requiredtype != null && !requiredtype.isinstance(bean)) else
} catch
(typemismatchexception var25)
throw
newbeannotofrequiredtypeexception
(name, requiredtype, bean.getclass());
}} else
}
在該方法裡面 string beanname = this.transformedbeanname(name);首先會通過
protected string transformedbeanname(string name)
beanfactoryutils.transformedbeanname(name)來判斷該name是否存在,以及判斷是否為&name,接著在canonicalname判斷map裡面是否存在這乙個鍵值對(載入所有bean成為map),
object sharedinstance = this.getsingleton(beanname);在方法裡面會判斷該bean實類的型別並返回,接下來會判斷是否存在,然後載入logger,
bean = this.getobjectforbeaninstance(sharedinstance, name, beanname, (rootbeandefinition)null);並且實類化
獲取bean的工具類
工具類,用於獲取spring中管理的bean import org.springframework.beans.bean ception import org.springframework.beans.factory.beanfactory import org.springframework.b...
spring獲取bean的方式
import org.springframework.beans.bean ception import org.springframework.beans.factory.nosuchbeandefinitionexception import org.springframework.contex...
Spring裝配Bean的過程
spring裝配bean的過程 1.例項化 2.設定屬性值 3.如果實現了beannameaware介面,呼叫setbeanname設定bean的id或者name 4.如果實現beanfactoryaware介面,呼叫setbeanfactory 設定beanfactory 6.呼叫beanpost...