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