SpringBoot生命周期

Spring Bean的生命周期

Bean容器找到配置文件中 Spring Bean 的定义。

Bean容器利用Java Reflection API创建一个Bean的实例。

如果涉及到一些属性值 利用set方法设置一些属性值。

如果Bean实现了BeanNameAware接口,调用setBeanName()方法,传入Bean的名字。

如果Bean实现了BeanClassLoaderAware接口,调用setBeanClassLoader()方法,传入ClassLoader对象的实例。

如果Bean实现了BeanFactoryAware接口,调用setBeanClassLoader()方法,传入ClassLoader对象的实例。

与上面的类似,如果实现了其他*Aware接口,就调用相应的方法。

如果有和加载这个Bean的Spring容器相关的BeanPostProcessor对象,执行postProcessBeforeInitialization()方法

如果Bean实现了InitializingBean接口,执行afterPropertiesSet()方法。

如果Bean在配置文件中的定义包含init-method属性,执行指定的方法。

如果有和加载这个Bean的Spring容器相关的BeanPostProcessor对象,执行postProcessAfterInitialization()方法

当要销毁Bean的时候,如果Bean实现了DisposableBean接口,执行destroy()方法。

当要销毁Bean的时候,如果Bean在配置文件中的定义包含destroy-method属性,执行指定的方法。

SpringBoot 应用程序启动过程

图片: SpringBoot生命周期
我们将各步骤总结精炼如下:

通过 SpringFactoriesLoader 加载 META-INF/spring.factories 文件,获取并创建 SpringApplicationRunListener 对象

然后由 SpringApplicationRunListener 来发出 starting 消息

创建参数,并配置当前 SpringBoot 应用将要使用的 Environment

完成之后,依然由 SpringApplicationRunListener 来发出 environmentPrepared 消息

创建 ApplicationContext

初始化 ApplicationContext,并设置 Environment,加载相关配置等

由 SpringApplicationRunListener 来发出 contextPrepared 消息,告知SpringBoot 应用使用的 ApplicationContext 已准备OK

将各种 beans 装载入 ApplicationContext,继续由 SpringApplicationRunListener 来发出 contextLoaded 消息,告知 SpringBoot 应用使用的 ApplicationContext 已装填OK

refresh ApplicationContext,完成IoC容器可用的最后一步

由 SpringApplicationRunListener 来发出 started 消息

完成最终的程序的启动

由 SpringApplicationRunListener 来发出 running 消息,告知程序已运行起来了