本文基于SpringBoot 2.5.0-M2
讲解Spring中Lifecycle
和SmartLifecycle
的作用和区别,以及如何控制SmartLifecycle的优先级。
并讲解SpringBoot中如何通过SmartLifecycle
来启动/停止web容器.
SmartLifecycle和Lifecycle作用
都是让开发者可以在所有的bean都创建完成(getBean) 之后执行自己的初始化工作,或者在退出时执行资源销毁工作。
SmartLifecycle和Lifecycle区别
1.SmartLifecycle
接口继承Lifecycle
接口,同时继承了org.springframework.context.Phased
接口用于控制多个SmartLifecycle
实现之间的优先级。
2.在SpringBoot应用中,或在Spring应用中没有调用AbstractApplicationContext#start
方法,如果一个Bean只是实现了Lifecycle
接口的情况下:
不会执行Lifecycle
接口中的启动方法,包括Lifecycle#isRunning
方法也不会被执行。
但是在应用 退出时 会执行Lifecycle#isRunning
方法判断该Lifecycle
是否已经启动,如果返回true则调用Lifecycle#stop()
停止方法。
3. 如果一个Bean实现了SmartLifecycle
接口,则会执行启动方法。先会被根据Phased
接口优先级分组,封装在LifecycleGroup
,然后循环调用LifecycleGroup#start()
方法,SmartLifecycle#isRunning
判断是否已经执行,返回false表示还未执行,则调用SmartLifecycle#start()
执行。Phased
返回值越小,优先级越高。
4.SmartLifecycle
中还有个isAutoStartup
方法,如果返回false
,在启动时也不会执行start方法,默认返回true
源码分析
SmartLifecycle
和Lifecycle
都是在org.springframework.context.support.DefaultLifecycleProcessor
中被调用,
DefaultLifecycleProcessor#onRefresh
方法在执行AbstractApplicationContext#finishRefresh
时会被调用,调用栈如下:
startBeans:142, DefaultLifecycleProcessor (org.springframework.context.support) onRefresh:123, DefaultLifecycleProcessor (org.springframework.context.support) finishRefresh:934, AbstractApplicationContext (org.springframework.context.support) refresh:585, AbstractApplicationContext (org.springframework.context.support) refresh:144, ServletWebServerApplicationContext (org.springframework.boot.web.servlet.context) refresh:755, SpringApplication (org.springframewor<i style="color:transparent">本文来源gaodai$ma#com搞$$代**码网$</i>k.boot) refreshContext:426, SpringApplication (org.springframework.boot) run:326, SpringApplication (org.springframework.boot) run:1299, SpringApplication (org.springframework.boot) run:1288, SpringApplication (org.springframework.boot) main:31, DemoApplication (com.example.demo)
DefaultLifecycleProcessor#onRefresh
源码:
@Override public void onRefresh() { startBeans(true); //autoStartupOnly = true this.running = true; }
DefaultLifecycleProcessor#startBeans
源码如下:
autoStartupOnly
在onRefresh时传入的是true,表示只执行可以自动启动的bean,即为:SmartLifecycle
的实现类,并且SmartLifecycle#isAutoStartup
返回值必须为true。
private void startBeans(boolean autoStartupOnly) { Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans(); Map<Integer, LifecycleGroup> phases = new TreeMap<>(); lifecycleBeans.forEach((beanName, bean) -> { if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) { int phase = getPhase(bean); phases.computeIfAbsent(phase, p -> new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly) ).add(beanName, bean); } }); if (!phases.isEmpty()) { phases.values().forEach(LifecycleGroup::start); } }