1. 生命周期的概要流程
Bean 的生命周期概括起来就是 4 个阶段:
实例化(Instantiation)
属性赋值(Populate)
初始化(Initialization)
销毁(Destruction)
Step1 实例化 Bean:根据配置文件中 Bean 的定义,利用 Java Reflection 反射技术创建 Bean 的实例
Step2 注入对象依赖的属性值(或对象)
Step3处理各种Aware接口:Spring 会检测该 Bean是否实现了 xxxAware接口,通过 Aware 类型的接口,可以让Spring框架为当前Bean注入相应的内容
1.·如果 Bean 实现 BeanNameAware 接口,会调用它实现的setBeanName(String beanId)方法,注入 Bean 的名字;。
2.如果Bean 实现BeanClassLoaderAware 接口,调用setBeanClassLoader()方法,注入 ClassLoader 对象的实例
3.如果 Bean 实现BeanFactoryAware 接口,会调用它实现的 setBeanFactory()方法,注入的是 Spring工厂;
4.如果 Bean 实现ApplicationContextAware 接口,会调用setApplicationContext()方法,注入 Spring上下文
Step4 执行BeanPostProcessor前置处理:如果想对Bean进行一些自定义的前置处理,那么可以让Bean实现了BeanPostProcessor 接口,将会在该阶段调用 postProcessBeforeInitiali zation(0bject obi, String s)方法。
Step5执行InitializingBean初始化方法:如果 Bean 实现了InitializingBean 接口,执行 afeterPropertiesSet()方法
Step6 执行init-method自定义初始化方法:如果Bean 在Spring 配置文件中配置了 init-method 属性,则会自动调用其配置的初始化方法。
.Step7执行BeanPostProcessor后置处理:如果这个Bean实现了BeanPostProcessor接口,将会调用postProcessAfterInitialization(0bject obi, Strings)方法,由于这个方法是在B ean 初始化结束后调用;
以上几个步骤完成后, Bean已经被正确创建,可以正常使用这个 Bean 了
Step8 执行DisposableBean销毁Bean:当 Bean不再需要时,会经过清理阶段,如果Bean实现了DisposableBean 这个接口,会调用其实现的 destrov()方法执行销毁
Step9执行destroy-method自定义销毁方法:如果这个Bean的Spring配置中配置了destroy-method属性,会自动调用其配置的自定义销毁方法