Spring中SmartLifecycle和Lifecycle的作用和区别

2024-08-31 18:08

本文主要是介绍Spring中SmartLifecycle和Lifecycle的作用和区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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

SmartLifecycle & Lifecycle作用和区别

SmartLifecycle和Lifecycle作用

  1. 都是让开发者可以在所有的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

源码分析

SmartLifecycleLifecycle都是在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.springframework.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 = truethis.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);}
}

而Spring AbstractApplicationContext#doClose退出时,无论是SmartLifecycleLifecycle都会执行isRunning方法,判断是否已经启动,返回true表示已经启动,则执行SmartLifecycleLifecyclestop方法。
源码见:org.springframework.context.support.DefaultLifecycleProcessor#doStop方法。

而执行AbstractApplicationContext#doClose一般是应用进程退出,通过jvm注册的钩子方法,或者应用程序编码调用。
AbstractApplicationContext#registerShutdownHook源码

@Override
public void registerShutdownHook() {if (this.shutdownHook == null) {// No shutdown hook registered yet.this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {@Overridepublic void run() {synchronized (startupShutdownMonitor) {doClose();}}};Runtime.getRuntime().addShutdownHook(this.shutdownHook);}
}

自定义LifecycleProcessor处理Lifecycle

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

org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration源码:

/*** {@link EnableAutoConfiguration Auto-configuration} relating to the application* context's lifecycle.** @author Andy Wilkinson* @since 2.3.0*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(LifecycleProperties.class)
public class LifecycleAutoConfiguration {@Bean(name = AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME)@ConditionalOnMissingBean(name = AbstractApplicationContext.LIFECYCLE_PROCESSOR_BEAN_NAME,search = SearchStrategy.CURRENT)public DefaultLifecycleProcessor defaultLifecycleProcessor(LifecycleProperties properties) {DefaultLifecycleProcessor lifecycleProcessor = new DefaultLifecycleProcessor();lifecycleProcessor.setTimeoutPerShutdownPhase(properties.getTimeoutPerShutdownPhase().toMillis());return lifecycleProcessor;}
}

SpringBoot中内嵌web容器启动时机

SpringBoo中就是通过实现SmartLifecycle来启动内嵌的web容器,实现类为WebServerStartStopLifecycle

ServletWebServerApplicationContextonRefresh方法中调用createWebServercreateWebServer方法中创建org.springframework.boot.web.server.WebServer实例,该对象则包含了控制web容器(tomcatjetty)的启动与停止方法。

@Override
protected void onRefresh() {super.onRefresh();try {createWebServer();}catch (Throwable ex) {throw new ApplicationContextException("Unable to start web server", ex);}
}

ServletWebServerApplicationContext#createWebServer源码:

private void createWebServer() {WebServer webServer = this.webServer;ServletContext servletContext = getServletContext();if (webServer == null && servletContext == null) {StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");ServletWebServerFactory factory = getWebServerFactory();createWebServer.tag("factory", factory.getClass().toString());this.webServer = factory.getWebServer(getSelfInitializer());createWebServer.end();getBeanFactory().registerSingleton("webServerGracefulShutdown",new WebServerGracefulShutdownLifecycle(this.webServer));getBeanFactory().registerSingleton("webServerStartStop",new WebServerStartStopLifecycle(this, this.webServer));}else if (servletContext != null) {try {getSelfInitializer().onStartup(servletContext);}catch (ServletException ex) {throw new ApplicationContextException("Cannot initialize servlet context", ex);}}initPropertySources();
}

createWebServer方法会将创建的webServer封装在WebServerStartStopLifecycle对象中,并注册到Spring容器中。

org.springframework.boot.web.servlet.context.WebServerStartStopLifecycle源码如下:

class WebServerStartStopLifecycle implements SmartLifecycle {private final ServletWebServerApplicationContext applicationContext;private final WebServer webServer;private volatile boolean running;WebServerStartStopLifecycle(ServletWebServerApplicationContext applicationContext, WebServer webServer) {this.applicationContext = applicationContext;this.webServer = webServer;}@Overridepublic void start() {this.webServer.start();this.running = true;this.applicationContext.publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext));}@Overridepublic void stop() {  this.webServer.stop();   }@Overridepublic boolean isRunning() {	return this.running;  }@Overridepublic int getPhase() {    return Integer.MAX_VALUE - 1;  }
}

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

SmartInitializingSingleton区别

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

不同点:

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

这篇关于Spring中SmartLifecycle和Lifecycle的作用和区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1124620

相关文章

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

SpringBoot使用ffmpeg实现视频压缩

《SpringBoot使用ffmpeg实现视频压缩》FFmpeg是一个开源的跨平台多媒体处理工具集,用于录制,转换,编辑和流式传输音频和视频,本文将使用ffmpeg实现视频压缩功能,有需要的可以参考... 目录核心功能1.格式转换2.编解码3.音视频处理4.流媒体支持5.滤镜(Filter)安装配置linu

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

Java使用MethodHandle来替代反射,提高性能问题

《Java使用MethodHandle来替代反射,提高性能问题》:本文主要介绍Java使用MethodHandle来替代反射,提高性能问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录一、认识MethodHandle1、简介2、使用方式3、与反射的区别二、示例1、基本使用2、(重要)

Java实现本地缓存的常用方案介绍

《Java实现本地缓存的常用方案介绍》本地缓存的代表技术主要有HashMap,GuavaCache,Caffeine和Encahche,这篇文章主要来和大家聊聊java利用这些技术分别实现本地缓存的方... 目录本地缓存实现方式HashMapConcurrentHashMapGuava CacheCaffe

SpringBoot整合Sa-Token实现RBAC权限模型的过程解析

《SpringBoot整合Sa-Token实现RBAC权限模型的过程解析》:本文主要介绍SpringBoot整合Sa-Token实现RBAC权限模型的过程解析,本文给大家介绍的非常详细,对大家的学... 目录前言一、基础概念1.1 RBAC模型核心概念1.2 Sa-Token核心功能1.3 环境准备二、表结

eclipse如何运行springboot项目

《eclipse如何运行springboot项目》:本文主要介绍eclipse如何运行springboot项目问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目js录当在eclipse启动spring boot项目时出现问题解决办法1.通过cmd命令行2.在ecl

Java中的Closeable接口及常见问题

《Java中的Closeable接口及常见问题》Closeable是Java中的一个标记接口,用于表示可以被关闭的对象,它定义了一个标准的方法来释放对象占用的系统资源,下面给大家介绍Java中的Clo... 目录1. Closeable接口概述2. 主要用途3. 实现类4. 使用方法5. 实现自定义Clos

Linux中的more 和 less区别对比分析

《Linux中的more和less区别对比分析》在Linux/Unix系统中,more和less都是用于分页查看文本文件的命令,但less是more的增强版,功能更强大,:本文主要介绍Linu... 目录1. 基础功能对比2. 常用操作对比less 的操作3. 实际使用示例4. 为什么推荐 less?5.

Jvm sandbox mock机制的实践过程

《Jvmsandboxmock机制的实践过程》:本文主要介绍Jvmsandboxmock机制的实践过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、背景二、定义一个损坏的钟1、 Springboot工程中创建一个Clock类2、 添加一个Controller