惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

The Hacker News
The Hacker News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
Recent Announcements
Recent Announcements
D
DataBreaches.Net
P
Proofpoint News Feed
V
Visual Studio Blog
J
Java Code Geeks
Recorded Future
Recorded Future
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Full Disclosure
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
C
Cybersecurity and Infrastructure Security Agency CISA
V
Vulnerabilities – Threatpost
罗磊的独立博客
Jina AI
Jina AI
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
G
GRAHAM CLULEY
Y
Y Combinator Blog
L
LangChain Blog
L
LINUX DO - 热门话题
宝玉的分享
宝玉的分享
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
云风的 BLOG
云风的 BLOG
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园_首页
A
About on SuperTechFans
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Latest news
Latest news
T
Threatpost
T
Tenable Blog
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Stack Overflow Blog
Stack Overflow Blog
C
Cisco Blogs
C
Check Point Blog
T
Tor Project blog
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
美团技术团队
I
Intezer
S
Securelist
AWS News Blog
AWS News Blog

博客园 - wastonl

Spring ResolvableType说明 Jvm内存以及垃圾回收相关知识 RocketMQ如何保证消息可靠性 RocketMQ整体架构 mybatis-plus易忘点笔记 SpringMVC使用Resource实现二进制传输(下载) Spring事件异步执行设计与实现 Spring Bean销毁机制 Zipkin Brave使用 Spring Boot日志系统简要介绍 spring cloud sleuth基本使用 Spring懒加载与@Lazy注解 tomcat自动刷新响应输出流缓冲区 https碎碎念 ES脚本使用 SpringMVC静态资源处理 Maven插件运行方式 如何使用Maven将项目中的依赖打进jar包 时区以及时区对于Java时间类格式化的影响 SpringMVC处理请求头、响应头、编码行为 tomcat连接处理机制和线程模型 树组件实现 JWT示例与原理 方法句柄API使用
Spring Lifecycle组件
wastonl · 2026-02-28 · via 博客园 - wastonl

简要介绍

Lifecycle组件是为了扩展bean的生命周期功能而增加的,它还有一个直接子类为SmartLifecycle接口,该接口能够控制组件生命周期的执行顺序。

下面是接口定义

public interface Lifecycle {

    
    void start();

    
    void stop();

    
    boolean isRunning();

}
public interface SmartLifecycle extends Lifecycle, Phased {

   
    int DEFAULT_PHASE = Integer.MAX_VALUE;

   
    default boolean isAutoStartup() {
        return true;
    }

    default void stop(Runnable callback) {
        stop();
        callback.run();
    }

  
    @Override
    default int getPhase() {
        return DEFAULT_PHASE;
    }
}

SmartLifecycle和Lifecycle区别如下

  • 实现SmartLifecycle接口的bean,在ApplicationContext初始化完成后(所有单例bean都已初始化),如果isAutoStartup方法返回true,则会自动调用start方法。而Lifecycle接口则需要手动调用ApplicationContext的start方法来触发。
  • SmartLifecycle接口可以控制执行顺序,它继承了Phased接口,getPhase方法返回的值越小,start()则越先调用,stop方法越晚执行。
  • SmartLifecycle增加了一个带有回调接口的stop,这样组件可以异步停止,回调callback是spring自己传递,就是一个CountDownLatch执行countDown方法,而主线程会执行CountDownLatch的await方法,等待组件stop方法执行完毕,当然这个等待时间由spring.lifecycle.timeout-per-shutdown-phase控制的,默认是30s。该参数不是等待所有的Lifecycle,执行时会根据phase来分组,是指每一个组的Lifecycle最多执行spring.lifecycle.timeout-per-shutdown-phase这么久,超了这个时间就执行下一个组了。
  • 另外ApplicationContext执行close方法时,不论是Lifecycle还是SmartLifecycle都会执行,前提是isRunning方法返回true。此时Lifecycle的phase会给0来参与分组排序。

因此只需要使用SmartLifecycle即可。

另外一个细节就是isRunning方法了,spring在调用start方法之前会先判断isRunning方法是不是返回false,调用stop方法之前会判断isRunning方法是不是返回true

实现模板

public class SimpleLifecycle implements SmartLifecycle {

    /**
     * 如果stop方法有异步线程, 则需要使用volatile修饰
     */
    private volatile boolean running;

    @Override
    public void start() {
        running = true;
        // doSomething
    }

    @Override
    public void stop() {
        running = false;
        // doSomething
    }

    @Override
    public boolean isRunning() {
        return running;
    }

    /**
     * 根据需要指定顺序
     */
    @Override
    public int getPhase() {
        return 0;
    }
}

执行时机源码

start生命周期

AbstractApplicationContext类

refresh -> finishRefresh -> getLifecycleProcessor().onRefresh()

触发SmartLifecycle执行的类为LifecycleProcessor

stop生命周期

AbstractApplicationContext类

close -> doClose -> lifecycleProcessor.onClose()

应用

tomcat容器的启动和关闭就是通过SmartLifecycle来实现的

  • WebServerStartStopLifecycle

  • WebServerGracefulShutdownLifecycle(开启优雅停机属性才有作用, server.shutdown=graceful),这样tomcat就会停止处理新的请求,会等待现有请求执行完毕。等待最大时间为spring.lifecycle.timeout-per-shutdown-phase,超过这个时间还没处理完成,WebServerStartStopLifecycle的stop方法就会执行了,会修改WebServerGracefulShutdownLifecycle循环的标记而退出。