關於spring的bean的生命週期

2021-10-09 08:28:59 字數 2162 閱讀 9575

spring通常通過配置檔案定義bean。如:

<?xml version=」1.0″ encoding=」utf-8″?>

id=」helloworld」

class

=」com.pqf.beans.helloworld」

>

name

=」msg」

>

>

helloworldvalue

>

property

>

bean

>

beans

>

這個配置檔案就定義了乙個標識為 helloworld 的bean。在乙個配置文件中可以定義多個bean。

有兩種方式初始化bean。

1、在配置文件中通過指定init-method 屬性來完成

在bean的類中實現乙個初始化bean屬性的方法,如init(),如:

public

class

helloworld

……}

然後,在配置檔案中設定init-mothod屬性:

id=」helloworld」

class

=」com.pqf.beans.helloworld」

init-mothod

=」init」

>

bean

>

2、實現org.springframwork.beans.factory.initializingbean介面

bean實現initializingbean介面,並且增加 afterpropertiesset() 方法:

public

class

helloworld implement initializingbean

……}

那麼,當這個bean的所有屬性被spring的beanfactory設定完後,會自動呼叫afterpropertiesset()方法對bean進行初始化,於是,配置檔案就不用指定 init-method屬性了。

helloworld hw=

newhelloworld()

;new

(hw)

;bw.

setpropertyvalue

(」msg」,」helloworld」)

;system.out.

println

(bw.

getpropertycalue

(」msg」)

);

2、使用beanfactory

inputstream is=

newfileinputstream

(」config.xml」)

;xmlbeanfactory factory=

newxmlbeanfactory

(is)

;helloworld hw=

(helloworld) factory.

getbean

(」helloworld」)

;system.out.

println

(hw.

getmsg()

);

new

(」config.xml」)

;helloworld hw=

(helloworld) actx.

getbean

(」helloworld」)

;system.out.

println

(hw.

getmsg()

);1、使用配置檔案中的 destory-method 屬性

與初始化屬性 init-methods類似,在bean的類中實現乙個撤銷bean的方法,然後在配置檔案中通過 destory-method指定,那麼當bean銷毀時,spring將自動呼叫指定的銷毀方法。

2、實現 org.springframwork.bean.factory.disposeblebean介面

如果實現了disposeblebean介面,那麼spring將自動呼叫bean中的destory方法進行銷毀,所以,bean中必須提供destory方法。

關於spring 的bean 裝配

foo foo foo foo1111 2222 42 www.cl.com www.cl1.com 1.單例項 預設 與原型bean singleton 為true 單例項模式,通過getbean或者裝配只能得到同一例項singleton 為false 原型模式,請求bean返回不同例項 2.例項...

Java面試之Spring的bean的生命週期

一 bean的定義 spring通常通過配置檔案定義bean。如 xmlns xsi xsi schemalocation spring beans 2.0.xsd helloworld 這個配置檔案就定義了乙個標識為 helloworld 的bean。在乙個配置文件中可以定義多個bean。二 be...

關於spring的bean配置繼承

bean配置繼承?顧名思義,是bean配置檔案的繼承,不是類的繼承,如下 乙個普通的bean package com.panguso.phl.bean public class user public void setname string name public long getid public...