spring技術內幕5 IoC容器的依賴注入

2021-06-22 14:33:55 字數 1812 閱讀 4242

1、當spring ioc容器完成了bean定義資源的定位、載入和解析註冊以後,ioc容器中已經管理類bean定義的相關資料,但是此時ioc容器還沒有對所管理的bean進行依賴注入,依賴注入在以下兩種情況發生:

(1)使用者第一次通過getbean方法向ioc容器索要bean時,ioc容器觸發依賴注入。

(2)當使用者在bean定義資源中為元素配置了lazy-init屬性,即讓容器在解析註冊bean定義時進行預例項化,觸發依賴注入。

beanfactory介面中定義了幾個getbean方法,就是使用者向ioc容器索取管理的bean的方法,我們通過分析其子類的具體實現,理解spring ioc容器在使用者索取bean時如何完成依賴注入。

2、使用者使用getbean方法向spring ioc容器索取被管理的bean:

//根據bean名稱,向容器獲取指定名稱的bean

public object getbean(string name) throws bean***ception ,getaccesscontrolcontext());

else,acc);

else,acc);

catch(privilegedactionexception ex){

throw ex.getexception();

else{

writemethod.invoke(this.object,value);

catch(typemismatchexception ex){

throw ex;

catch(invocationtargetexception ex){

propertychangeevent propertychangeevent =

new propertychangeevent(this.rootobject,this.nestedpath + propertyname,oldvalue,pv.getvalue());

if(ex.gettargetexception() instanceof classcastexception){

throw new typemismatchexception(propertychangeevent,pd.getpropertytype(),ex.gettargetexception());

else {

throw new methodinvocationexception(propertychangeevent,ex.gettargetexception());

catch(exception ex){

propertychangeevent pce = new propertychangeevent(this.rootobject,this.nestedpath + propertyname,oldvalue,pv.getvalue());

throw new methodinvocationexception(pce,ex);

通過上面依賴注入**的分析,我們已經明白了spring ioc容器時如何將屬性的值注入到bean例項物件中去的:

(1)對於集合型別的屬性,將其屬性值解析為目標型別的集合後直接賦值給屬性

(2)對於非集合型別的屬性,大量使用了jdk的反射和內省機制,通過屬性的getter方法獲取指定屬性注入以前的值,同時呼叫屬性的setter方法為屬性設定注入以後的值。

至此spring ioc容器對bean定義資源檔案的定位、載入、解析、依賴注入已經全部分析完畢,現在spring ioc容器中管理了一系列依靠依賴關係聯絡起來的bean,引用程式不需要自己手動建立所需的物件,spring ioc容器會在我們使用的時候自動為我們建立,並且為我們注入好相關的依賴,這就是sring核心功能的控制反轉和依賴注入的相關相關功能。

Spring系列 5 IOC技術

說實話,我對spring技術還是不算很了解,ioc的技術我在實體框架技術中提到過,但ioc和aop作為spring技術的兩個核心思想,我覺得在總結之前,還是有必要說明一下我所理解的ioc.我們知道,如果兩個事務之間存在邏輯關係,而且你需要根據這個邏輯關係做事,比如類a和類b,類a需要呼叫類b的方法,...

Spring系列 5 IOC技術

說實話,我對spring技術還是不算很了解,ioc的技術我在實體框架技術中提到過,但ioc和aop作為spring技術的兩個核心思想,我覺得在總結之前,還是有必要說明一下我所理解的ioc.我們知道,如果兩個事務之間存在邏輯關係,而且你需要根據這個邏輯關係做事,比如類a和類b,類a需要呼叫類b的方法,...

5 IOC工廠模式

定位資源 resource resource new filesystemresource new file src main resources conf spring mybatis.xml beanfactory beanfactory new xmlbeanfactory resource ...