(转) spring bean生命周期
Spring bean对象生命周期管理
Spring bean对象的生命周期管理包括Bean的创建装配和Bean的销毁两个过程。在了解Spring bean对象生命周期管理内容之前,首先来整理一下Spring对每个Bean进行管理扩展接口有哪些?
BeanNameAware
Spring在注册当前Bean到容器中时,会把当前Bean的Id值作为参数回调用到该接口方法
BeanClassLoaderAware
Spring在注册当前Bean到容器中时,会把当前Bean Class所属的ClassLoader对象作为参数回调该接口方法
BeanFactoryAware
Spring在注册当前Bean到容器中时,会把当前Bean对象所属的BeanFactory工厂对象实例作为参数回调该接口方法
ResourceLoaderAware
Spring在注册当前Bean到容器中时,会把ResourceLoader对象实例作为参数回调该接口方法. ResourceLoader对象方便的提供基于Classpath方式的Resource文件查找和定位功能。例如:
Resource template = rl.getResource("some/resource/path/myTemplate.txt");
ApplicationEventPublisherAware
Spring在注册当前Bean到容器中时,会把ApplicationEventPublisher对象实例作为参数回调该接口方法. ApplicationEventPublisher对象用于对所有监听ApplicationListener接口事件的对象,发布ApplicationEvent事件。
MessageSourceAware
Spring在注册当前Bean到容器中时,会把MessageSource对象实例作为参数回调该接口方法. MessageSource用于处理Spring的信息资源对象,如国际化信息处理
ApplicationContextAware
Spring在注册当前Bean到容器中时,会把ApplicationContext对象实例作为参数回调该接口方法.
ServletContextAware
Spring在注册当前Bean到容器中时,会把ServletContext对象实例作为参数回调该接口方法. 这个只在基于Web的ApplicationContext才会启用
BeanPostProcessors
Spring在对Bean象进行实例化前后,回调相应的方法。
InitializingBean
Spring容器完成Bean对象所有properties属性的依赖装配后,回调该接口方法。
DisposableBean
Spring Bean创建过程如下:
|
1 |
触发 BeanNameAware 的setBeanName方法 |
|
2 |
触发BeanClassLoaderAware的setBeanClassLoader方法 |
|
3 |
触发BeanFactoryAware's setBeanFactory |
|
4 |
触发ResourceLoaderAware's setResourceLoader (only applicable when running in an application context) |
|
5 |
触发ApplicationEventPublisherAware的setApplicationEventPublisher方法 (只在由application context启动时工作) |
|
6 |
触发MessageSourceAware的 setMessageSource 方法(只在由application context启动时工作) |
|
7 |
触发ApplicationContextAware'的setApplicationContext方法 (只在由application context启动时工作) |
|
8 |
触发ServletContextAware的setServletContext 方法(只web application context下启用) |
|
9 |
触发BeanPostProcessors的postProcessBeforeInitialization方法 |
|
10 |
触发InitializingBean的 afterPropertiesSet方法 |
|
11 |
触发用户在XML文件中配置的”init-method” 指定的方法名。不指定则跳过 |
|
12 |
触发BeanPostProcessors 的postProcessAfterInitialization 方法 |
Spring Bean销毁过程如下:
|
1 |
触发 DisposableBean的destroy方法 |
|
2 |
触发用户在XML文件中配置的” destroy-method” 指定的方法名。不指定则跳过 |

浙公网安备 33010602011771号