容器是spring的核心,spring容器使用di管理所有組成應用系統的元件。
spring的ioc容器能夠幫我們自動new物件,物件交給spring管之後我們不用自己手動去new物件了。
1.1 bean工廠(由beanfactory介面定義)是最簡單的spring容器,提供了基本的依賴注入支援。
採用工廠設計模式,就是說由這個類負責建立和分發bean。
2.1 xmlbeanfactory
spring中有幾種beanfactory的實現 其中最常用的是xmlbeanfactory。
使用xmlbeanfactory讀取spring配置檔案,可以如下:
------下面是spring配置部分:
$$$
$$
$$
beanfactory factory=new xmlbeanfactory(resource);
上面的**告訴bean工廠從xml檔案中讀取bean的定義資訊。但是現在bean工廠還沒有本例項化bean。
bean是被延遲載入到bean工廠中的,就是說bean工廠會立刻把bean的基本資訊載入進來,但是bean只有在需要的時候才會被例項化。
為了從bean工廠得到乙個bean,只要簡單地呼叫getbean()方法。
com.geostar.query.beans.datasource ds=(com.geostar.query.beans.datasource)factory.getbean("ds");
system.out.println(ds.getdriverclassname());
當getbean()方法被呼叫的時候,工廠就會例項化bean並且使用依賴注入設定bean的屬性。這樣就在spring容器裡面開始了bean的生命。
datasource ds=(datasource)factory.getbean("ds");
system.out.println(ds.getdriverclassname());
第一種和第二種的區別在於,classpath可以在整個類路徑(包括jar檔案)中尋找定義bean的xml檔案;而filesystem只能在指定路徑中尋找。
// or ~
2 兩者在載入bean例項時的區別:
beanfactory被初始化的時候,並沒有載入所有的單例項bean物件,而是等到呼叫getbean()方法的時候才初始化相應的bean例項物件。
5.1 bean的定義
spring通常通過配置檔案定義bean。如:
helloworld
這個配置檔案就定義了乙個標識為 helloworld 的bean。在乙個配置文件中可以定義多個bean。
5.2 bean的初始化
有兩種方式初始化bean。
5.2.1在配置文件中通過指定init-method 屬性來完成
在bean的類中實現乙個初始化bean屬性的方法,如init(),如:
public class helloworld
……}
然後,在配置檔案中設定init-mothod屬性:
5.2.2 實現 org.springframwork.beans.factory.initializingbean介面
bean實現initializingbean介面,並且增加 afterpropertiesset() 方法:
public class helloworld implement initializingbean
……}
那麼,當這個bean的所有屬性被spring的beanfactory設定完後,會自動呼叫afterpropertiesset()方法對bean進行初始化,於是,配置檔案就不用指定 init-method屬性了。
5.3 bean的呼叫
helloworld hw=new helloworld();
bw.setpropertyvalue(「msg」,」helloworld」);
system.out.println(bw.getpropertycalue(「msg」));
5.3.2 使用beanfactory
inputstream is=new fileinputstream(「config.xml」);
xmlbeanfactory factory=new xmlbeanfactory(is);
helloworld hw=(helloworld) factory.getbean(「helloworld」);
system.out.println(hw.getmsg());
helloworld hw=(helloworld) actx.getbean(「helloworld」);
system.out.println(hw.getmsg())
5.4 bean的銷毀
5.4.1 用配置檔案中的 destory-method 屬性
與初始化屬性 init-methods類似,在bean的類中實現乙個撤銷bean的方法,然後在配置檔案中通過 destory-method指定,那麼當bean銷毀時,spring將自動呼叫指定的銷毀方法。
5.4.2 實現 org.springframwork.bean.factory.disposeblebean介面
如果實現了disposeblebean介面,那麼spring將自動呼叫bean中的destory方法進行銷毀,所以,bean中必須提供destory方法。
參考:
Spring原始碼解讀之bean注入依賴
在應用開發中 以應用開發人員的身份訪問設計元件時候,往往需要引用 或者呼叫其他組建的服務,這種依賴關係如果固定在元件設計中就會造成 依賴關係的僵化和維護難度的增加。在 spring 中通過ioc 容器把資源的獲取方 向反轉,讓 ioc容器住的管理這些依賴關係,將這些關係注入到元件中,那麼會讓這些依賴...
spring 基本Bean裝配
在基於spring的應用中,應用元件在spring中是啟用的。容器可以建立元件,裝配和配置元件,以及管理它們的整個生 命週期。容器是spring 框架的核心,spring容器使用di管理所有組成應用系統的元件。spring容器提供多個spring 容器。spring容器提供了多種容器,並分為兩類。b...
詳細例項,解讀spring容器中bean的生命週期
下面新增此次測試demo的工程樣例截圖 下面為完整的測試檔案 1 beanlifecycle package springioc import org.springframework.beans.bean ception import org.springframework.beans.factor...