總結(jié)下 Spring Bean 生命周期流程,大概是這樣的:
- Bean 容器找到配置文件中 Spring Bean 的定義。
- Bean 容器利用 Java Reflection API 創(chuàng)建 Bean 的實(shí)例。
- 如果涉及到屬性值,就利用 set 方法進(jìn)行設(shè)置。
- 如果 Bean 實(shí)現(xiàn)了 BeanNameAware 接口,就調(diào)用 setBeanName() 方法,并傳入 Bean 的名字。
- 如果 Bean 實(shí)現(xiàn)了 BeanClassLoaderAware 接口,就調(diào)用 setBeanClassLoader() 方法,以及傳入 ClassLoader 對(duì)象的實(shí)例。
- 如果 Bean 實(shí)現(xiàn)了 BeanFactoryAware 接口,調(diào)用 setBeanClassLoader() 方法,傳入 ClassLoader 對(duì)象的實(shí)例。
- 與上面的類似,如果實(shí)現(xiàn)了其他 Aware 接口,就調(diào)用相應(yīng)的方法。
- 如果有和加載這個(gè) Bean 的 Spring 容器相關(guān)的 BeanPostProcessor 對(duì)象,執(zhí)行 postProcessBeforeInitialization() 方法
- 如果 Bean 實(shí)現(xiàn)了 InitializingBean 接口,執(zhí)行 afterPropertiesSet() 方法。
- 如果 Bean 在配置文件中的定義包含 init-method 屬性,執(zhí)行指定的方法。
- 如果有和加載這個(gè) Bean 的 Spring 容器相關(guān)的 BeanPostProcessor 對(duì)象,執(zhí)行 postProcessAfterInitialization() 方法
- 當(dāng)要銷毀 Bean 的時(shí)候,如果 Bean 實(shí)現(xiàn)了 DisposableBean 接口,執(zhí)行 destroy() 方法。
- 當(dāng)要銷毀 Bean 的時(shí)候,如果 Bean 在配置文件中的定義包含 destroy-method 屬性,執(zhí)行指定的方法。

Spring Bean 生命周期流程

Spring Bean 生命周期流程