在Spring中,从BeanFactory或ApplicationContext取得的实例为 Singleton,预设是每一个Bean别名维持一个实例,对单执行绪的程序来说并不会有什么问题,但对于多执行绪的程序,您必须注意到执行绪安全,您也可以设定每次取得Bean时都产生一个新的实例,例如:
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean" singleton="false">
singleton属性预设是true,藉由将其设定为false,每次取得Bean时都会产生一个新的实例。
一个Bean从建立到销毁,会历经几个执行阶段,如果是使用BeanFactory来管理Bean的话:
可以在Bean定义文件使用init-method属性设定方法名称,例如:
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean" init-method="initBean">
如果有以上设定的话,则进行至这个阶段时,就会执行initBean()方法。
在容器关闭时,可以在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()及之后的流程。