kela的筆記 應(yīng)用程序框架 ---- spring(5)
Posted on 2006-08-23 17:36 Kela 閱讀(299) 評(píng)論(0) 編輯 收藏 所屬分類: 我的筆記(Spring)
摘要:Bean的生命周期。一個(gè)Bean從建立到銷毀,如果是使用BeanFactory來生成,管理Bean的話,會(huì)經(jīng)歷幾個(gè)執(zhí)行階段。
●????
Bean
的建立
由BeanFactory讀取Bean定義文件,并生成各個(gè)Bean實(shí)例。
在Spring中,默認(rèn)取得的實(shí)例為Singleton模式,即每一次context.getBean(“beanName”)取得的對(duì)象都是同一個(gè),而不是每次都產(chǎn)生一個(gè)新的對(duì)象。大部分情況下Singleton是能夠滿足要求的,如果考慮到線程安全等的問題,需使用Prototype模式,即每次取得的對(duì)象都是一個(gè)獨(dú)立的對(duì)象,只需要將singleton=”false”即可。
如:
<bean
id=
"someBean"
class=
"com.kela.spring.ioc.SomeBean"
singleton=
"false"
>
●????
屬性注入
執(zhí)行相關(guān)的Bean屬性依賴注入
●????
BeanNameAware
的setBeanName()
如果Bean類有實(shí)現(xiàn)org.springframework.beans.factory.BeanNameAware接口,則執(zhí)行它的setBaenName()方法。
實(shí)現(xiàn)BeanNameAware接口的Bean類,在依賴關(guān)系設(shè)定完成后,初始化方法之前,將Bean的定義文件中的名稱設(shè)定給Bean。
注:Spring中提供了一些Aware相關(guān)接口,實(shí)現(xiàn)這些Aware接口的Bean類在被初始化之后,可以取得一些Spring所提供的資源或使用某些功能。
一旦實(shí)現(xiàn)了提供的相關(guān)接口,則應(yīng)用程序就會(huì)使用到Spring的相關(guān)API,而與Spring產(chǎn)生耦合關(guān)系。
●????
BeanFactoryAware
的setBeanFactory()
如果bean類有實(shí)現(xiàn)org.springframework.beans.factory.BeanFactoryAware接口,則執(zhí)行它的setBeanFactory。
實(shí)現(xiàn)BeanFactoryAware接口的Bean類,在依賴關(guān)系設(shè)定完成后,初始化方法之前,Spring容器將會(huì)注入BeanFactory的實(shí)例。
●????
BeanPostProcessor
的postProcessBeforeInitialization()
如果任何的org.springfaramwork.beans.factory.config.BeanPostProcessor實(shí)例與Bean實(shí)例關(guān)聯(lián),則執(zhí)行BeanPostProcessors實(shí)例的postProcessBeforeInitialization()方法。
●????
InitializingBean
的afterPropertiesSet()
如果Bean類以實(shí)現(xiàn)org.springfaramwork.beans.factory.InitializingBean接口,則執(zhí)行它的afterPropertiesSet()方法。
●????
Bean
定義文件中定義init-method
可以在Bean定義文件使用“init-method”屬性設(shè)定方法名稱,例如:
<bean
id=
"someBean"
class=
"com.kela.spring.ioc.SomeBean"
init-method=
"initBean"
>
如果有以上設(shè)定的話,則進(jìn)行至這個(gè)階段時(shí),就會(huì)執(zhí)行initBean()方法。
●????
BeanPostProcessor
的postProcessAfterInitialization()
如果任何的org.springfaramwork.beans.factory.config.BeanPostProcessor實(shí)例與Bean實(shí)例關(guān)聯(lián),則執(zhí)行BeanPostProcessors實(shí)例的postProcessAfterInitialization()方法。
●????
DisposableBean
的destroy()
在容器關(guān)閉時(shí),如果Bean類有實(shí)現(xiàn)org.springframework.beans.factory.DisposableBean接口,則執(zhí)行它的destroy()方法。
●????
Bean
定義文件中定義destroy-method
在容器關(guān)閉時(shí),可以在Bean定義文件中使用“destroy-method”屬性設(shè)定方法名稱,例如:
…
<bean
id=
"someBean"
class=
"com.kela.spring.ioc.SomeBean"
destroy-method=
"destroyBean"
>
如果有以上設(shè)定的話,則進(jìn)行至這個(gè)階段時(shí),就會(huì)執(zhí)行destroyBean()方法。
注意:如果是使用ApplicationContext來生成并管理Bean的話則稍有不同,使用ApplicationContext來生成及管理Bean實(shí)例的話,在執(zhí)行BeanFactoryAware的setBeanFactory()階段之后,若Bean類上有實(shí)現(xiàn)org.springframework.context.ApplicationContextAware接口,則執(zhí)行其setApplicationContext()方法,接著才繼續(xù)進(jìn)行BeanPostProcessor的postProcessBeforeInitialization()及之后的流程。