ITEEDU

Spring Gossip: Bean 的生命周期

在Spring中,从BeanFactory或ApplicationContext取得的实例为 Singleton,预设是每一个Bean别名维持一个实例,对单执行绪的程序来说并不会有什么问题,但对于多执行绪的程序,您必须注意到执行绪安全,您也可以设定每次取得Bean时都产生一个新的实例,例如:

<bean id="helloBean"
	class="onlyfun.caterpillar.HelloBean"
	singleton="false">

singleton属性预设是true,藉由将其设定为false,每次取得Bean时都会产生一个新的实例。

一个Bean从建立到销毁,会历经几个执行阶段,如果是使用BeanFactory来管理Bean的话:

  • Bean的建立
由BeanFactory读取Bean定义档,并生成各个Bean实例。

  • 属性注入
执行相关的Bean属性依赖注入。

  • BeanNameAware的setBeanName()
如果Bean类别有实作org.springframework.beans.factory.BeanNameAware接口,则执行它的setBeanName()方法。

  • BeanFactoryAware的setBeanFactory()
如果Bean类别有实作org.springframework.beans.factory.BeanFactoryAware接口,则执行它的setBeanFactory()方法。

  • BeanPostProcessors的processBeforeInitialization()
如果有任何的BeanPostProcessors实例与Bean实例关联,则执行BeanPostProcessors实例的processBeforeInitialization()方法。

  • InitializingBean的afterPropertiesSet()
如果Bean类别有实作org.springframework.beans.factory.InitializingBean,则执行它的afterPropertiesSet()方法。

  • Bean定义档中定义init-method

可以在Bean定义文件使用init-method属性设定方法名称,例如:

<bean id="helloBean"
	class="onlyfun.caterpillar.HelloBean"
	init-method="initBean">

如果有以上设定的话,则进行至这个阶段时,就会执行initBean()方法。

  • BeanPostProcessors的processaAfterInitialization()
如果有任何的BeanPostProcessors实例与Bean实例关联,则执行BeanPostProcessors实例的processaAfterInitialization()方法。

  • DisposableBean的destroy()
在容器关闭时,如果Bean类别有实作org.springframework.beans.factory.DisposableBean,则执行它的destroy()方法。

  • Bean定义档中定义destroy-method

在容器关闭时,可以在Bean定义文件使用destroy-method属性设定方法名称,例如:

<bean id="helloBean"
	class="onlyfun.caterpillar.HelloBean"
	destroy-method="destroyBean">

如果有以上设定的话,则进行至这个阶段时,就会执行destroyBean()方法。


如果是使用ApplicationContext来管理Bean的话,则在执行BeanFactoryAware的setBeanFactory()阶段 之后,若Bean有实作org.springframework.context.ApplicationContextAware接口,则执行其 setApplicationContext()方法,接着才继续进行BeanPostProcessors的 processBeforeInitialization()及之后的流程。