Java SpringBoot
基于SpringBoot 2.5.0-M2了解Spring中LifecycleSmartLifecycle的作用和区别,以及如何控制SmartLifecycle的优先级。
并了解SpringBoot中如何通过SmartLifecycle来启动/停止web容器.

SmartLifecycle& Lifecycle作用和区别

SmartLifecycleLifecycle作用
都是让开发者可以在所有的bean都创建完成(getBean) 之后执行自己的初始化工作,或者在退出时执行资源销毁工作。
SmartLifecycleLifecycle区别

  • SmartLifecycle接口继承Lifecycle接口,同时继承了org.springframework.context.Phased接口用于控制多个SmartLifecycle实现之间的优先级。
  • 在SpringBoot应用中,或在Spring应用中没有调用AbstractApplicationContext#start方法,如果一个Bean只是实现了Lifecycle接口的情况下:
    • 不会执行Lifecycle接口中的启动方法,包括Lifecycle#isRunning方法也不会被执行。
    • 但是在应用 退出时 会执行Lifecycle#isRunning方法判断该Lifecycle是否已经启动,如果返回true则调用Lifecycle#stop()停止方法。
  • 如果一个Bean实现了SmartLifecycle接口,则会执行启动方法。先会被根据Phased接口优先级分组,封装在LifecycleGroup,然后循环调用LifecycleGroup#start()方法,SmartLifecycle#isRunning判断是否已经执行,返回false表示还未执行,则调用SmartLifecycle#start()执行。Phased返回值越小,优先级越高。
  • SmartLifecycle中还有个isAutoStartup方法,如果返回false,在启动时也不会执行start方法,默认返回true

    源码分析

    SmartLifecycleLifecycle都是在org.springframework.context.support.DefaultLifecycleProcessor中被调用,DefaultLifecycleProcessor#onRefresh方法在执行AbstractApplicationContext#finishRefresh时会被调用,调用栈如下:

    1. startBeans:142, DefaultLifecycleProcessor (org.springframework.context.support)
    2. onRefresh:123, DefaultLifecycleProcessor (org.springframework.context.support)
    3. finishRefresh:934, AbstractApplicationContext (org.springframework.context.support)
    4. refresh:585, AbstractApplicationContext (org.springframework.context.support)
    5. refresh:144, ServletWebServerApplicationContext (org.springframework.boot.web.servlet.context)
    6. refresh:755, SpringApplication (org.springframework.boot)
    7. refreshContext:426, SpringApplication (org.springframework.boot)
    8. run:326, SpringApplication (org.springframework.boot)
    9. run:1299, SpringApplication (org.springframework.boot)
    10. run:1288, SpringApplication (org.springframework.boot)
    11. main:31, DemoApplication (com.example.demo)

    DefaultLifecycleProcessor#onRefresh源码:

    1. @Override
    2. public void onRefresh() {
    3. startBeans(true); //autoStartupOnly = true
    4. this.running = true;
    5. }

    DefaultLifecycleProcessor#startBeans源码如下:
    autoStartupOnlyonRefresh时传入的是true,表示只执行可以自动启动的bean,即为:SmartLifecycle的实现类,并且SmartLifecycle#isAutoStartup返回值必须为true。

    1. private void startBeans(boolean autoStartupOnly) {
    2. Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
    3. Map<Integer, LifecycleGroup> phases = new TreeMap<>();
    4. lifecycleBeans.forEach((beanName, bean) -> {
    5. if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
    6. int phase = getPhase(bean);
    7. phases.computeIfAbsent(phase, p ->
    8. new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly)
    9. ).add(beanName, bean);
    10. }
    11. });
    12. if (!phases.isEmpty()) {
    13. phases.values().forEach(LifecycleGroup::start);
    14. }
    15. }

    而Spring AbstractApplicationContext#doClose退出时,无论是SmartLifecycleLifecycle都会执行isRunning方法,判断是否已经启动,返回true表示已经启动,则执行SmartLifecycleLifecyclestop方法。源码见:org.springframework.context.support.DefaultLifecycleProcessor#doStop方法。
    而执行AbstractApplicationContext#doClose一般是应用进程退出,通过jvm注册的钩子方法,或者应用程序编码调用。
    AbstractApplicationContext#registerShutdownHook源码

    1. @Override
    2. public void registerShutdownHook() {
    3. if (this.shutdownHook == null) {
    4. // No shutdown hook registered yet.
    5. this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
    6. @Override
    7. public void run() {
    8. synchronized (startupShutdownMonitor) {
    9. doClose();
    10. }
    11. }
    12. };
    13. Runtime.getRuntime().addShutdownHook(this.shutdownHook);
    14. }
    15. }

    自定义LifecycleProcessor处理Lifecycle

    在源码分析中提到了DefaultLifecycleProcessor,其实现了LifecycleProcessor接口。然而自己也可以实现该接口,替换默认的DefaultLifecycleProcessor。SpringBoot中则是自己配置了DefaultLifecycleProcessor,可以按照同样的方式,覆盖默认的实现。例如可以让Lifecycle中的start()方法在onRefresh()时也能被执行。
    org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration源码:

    1. /**
    2. * {@link EnableAutoConfiguration Auto-configuration} relating to the application
    3. * context's lifecycle.
    4. *
    5. * @author Andy Wilkinson
    6. * @since 2.3.0
    7. */
    8. @Configuration(proxyBeanMethods = false)
    9. @EnableConfigurationProperties(LifecycleProperties.class)
    10. public class LifecycleAutoConfiguration {
    11. @Bean(name = AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME)
    12. @ConditionalOnMissingBean(name = AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME,
    13. search = SearchStrategy.CURRENT)
    14. public DefaultLifecycleProcessor defaultLifecycleProcessor(LifecycleProperties properties) {
    15. DefaultLifecycleProcessor lifecycleProcessor = new DefaultLifecycleProcessor();
    16. lifecycleProcessor.setTimeoutPerShutdownPhase(properties.getTimeoutPerShutdownPhase().toMillis());
    17. return lifecycleProcessor;
    18. }
    19. }

    SpringBoot中内嵌web容器启动时机

    SpringBoot中就是通过实现SmartLifecycle来启动内嵌的web容器,实现类为WebServerStartStopLifecycle
    ServletWebServerApplicationContextonRefresh方法中调用createWebServercreateWebServer方法中创建org.springframework.boot.web.server.WebServer实例,该对象则包含了控制web容器(tomcat、jetty)的启动与停止方法。

    1. @Override
    2. protected void onRefresh() {
    3. super.onRefresh();
    4. try {
    5. createWebServer();
    6. }catch (Throwable ex) {
    7. throw new ApplicationContextException("Unable to start web server", ex);
    8. }
    9. }

    ServletWebServerApplicationContext#createWebServer源码:

    1. private void createWebServer() {
    2. WebServer webServer = this.webServer;
    3. ServletContext servletContext = getServletContext();
    4. if (webServer == null && servletContext == null) {
    5. StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");
    6. ServletWebServerFactory factory = getWebServerFactory();
    7. createWebServer.tag("factory", factory.getClass().toString());
    8. this.webServer = factory.getWebServer(getSelfInitializer());
    9. createWebServer.end();
    10. getBeanFactory().registerSingleton("webServerGracefulShutdown",
    11. new WebServerGracefulShutdownLifecycle(this.webServer));
    12. getBeanFactory().registerSingleton("webServerStartStop",
    13. new WebServerStartStopLifecycle(this, this.webServer));
    14. }
    15. else if (servletContext != null) {
    16. try {
    17. getSelfInitializer().onStartup(servletContext);
    18. }
    19. catch (ServletException ex) {
    20. throw new ApplicationContextException("Cannot initialize servlet context", ex);
    21. }
    22. }
    23. initPropertySources();
    24. }

    createWebServer方法会将创建的webServer封装在WebServerStartStopLifecycle对象中,并注册到Spring容器中。
    org.springframework.boot.web.servlet.context.WebServerStartStopLifecycle源码如下:

    1. class WebServerStartStopLifecycle implements SmartLifecycle {
    2. private final ServletWebServerApplicationContext applicationContext;
    3. private final WebServer webServer;
    4. private volatile boolean running;
    5. WebServerStartStopLifecycle(ServletWebServerApplicationContext applicationContext, WebServer webServer) {
    6. this.applicationContext = applicationContext;
    7. this.webServer = webServer;
    8. }
    9. @Override
    10. public void start() {
    11. this.webServer.start();
    12. this.running = true;
    13. this.applicationContext
    14. .publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext));
    15. }
    16. @Override
    17. public void stop() { this.webServer.stop(); }
    18. @Override
    19. public boolean isRunning() { return this.running; }
    20. @Override
    21. public int getPhase() { return Integer.MAX_VALUE - 1; }
    22. }

    WebServerStartStopLifecycle则实现了SmartLifecycle接口,当Spring回调到SmartLifecycle接口方法时则调用this.webServer.start();启动web容器,web容器启动完成之后会通过applicationContext发布ServletWebServerInitializedEvent事件,表示web容器启动成功,可以接收http请求。

    SmartInitializingSingleton区别

    相同点:SmartInitializingSingletonLifecycleSmartLifecycle都是在所有的单实例bean创建(getBean方法)之后执行。
    不同点:

  • SmartInitializingSingleton优先于LifecycleSmartLifecycle执行。

  • SmartInitializingSingleton只有一个afterSingletonsInstantiated方法。而Lifecyclestart,stop,isRunning等方法。
  • 多个SmartInitializingSingleton实现之间无法排序控制执行的顺序,而SmartLifecycle实现了Phased接口,可以通过int getPhase()控制执行循序。
  • SmartInitializingSingleton之间可以通过@DependsOn来控制执行顺序,但这是由Spring中@DependsOn注解的作用及原理来实现的,并不是对SmartInitializingSingleton做了排序。