SpringBoot中SmartLifecycle的使用解析
前言
SmartLifecycle是一個擴展了Lifecycle接口,可以跟蹤spring容器ApplicationContext刷新或者關(guān)閉的接口,實現(xiàn)該接口的實現(xiàn)類有特定的執(zhí)行順序。
當ApplicationContext刷新時,所有bean都加載和初始化完成后,根據(jù)isAutoStartup和isRunning判斷是否自動執(zhí)行start()
1.新建TestSmartLifecycle類
public class TestSmartLifecycle implements SmartLifecycle {
@Override
public void start() {
System.out.println("TestSmartLifecycle is start");
}
//SmartLifecycle組件停止后的回調(diào),程序被異步關(guān)閉
@Override
public void stop() {
System.out.println("SmartLifecycle is stop");
}
//為false,并且isAutoStartup為true,執(zhí)行start方法
//為true,執(zhí)行stop方法。
@Override
public boolean isRunning() {
return false;
}
//如果為true,實現(xiàn)了SmartLifecycle 接口的組件,能再ApplicationContext已經(jīng)刷新的時候,自動執(zhí)行start方法,
@Override
public boolean isAutoStartup() {
return true;
}
//當running為true時,再應用關(guān)閉時會執(zhí)行stop(Runnable callback)方法,
如果再執(zhí)行完stop后,running沒有設置為false時,應用會卡住一段時間,無法退出
@Override
public void stop(Runnable callback) {
System.out.println("TestSmartLifecycle is stop");
callback.run();
}
@Override
public int getPhase() {
return 0;
}
}2.配置Bean
@Configuration
public class TestConfiguration {
@Bean
TestSmartLifecycle testSmartLifecycle(){
return new TestSmartLifecycle();
}
}3.debugger啟動應用程序
可以看見如下的調(diào)用鏈,大致是SpringApplication.run(CommonsTestApplication.class, args)-->refreshContext-->refresh-->startBeans-->start,其中,再startBean中獲取了所有實現(xiàn)SmartLifecycle的非懶加載的bean,并再start方法中,調(diào)用對應實現(xiàn)bean的start方法,執(zhí)行相應的邏輯,具體可看下面截圖。

private void startBeans(boolean autoStartupOnly) {
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
Map<Integer, LifecycleGroup> phases = new HashMap<>();
lifecycleBeans.forEach((beanName, bean) -> {
if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
int phase = getPhase(bean);
LifecycleGroup group = phases.get(phase);
if (group == null) {
group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
phases.put(phase, group);
}
group.add(beanName, bean);
}
});
if (!phases.isEmpty()) {
List<Integer> keys = new ArrayList<>(phases.keySet());
Collections.sort(keys);
for (Integer key : keys) {
phases.get(key).start();
}
}
}

到此這篇關(guān)于SpringBoot中SmartLifecycle的使用解析的文章就介紹到這了,更多相關(guān)SmartLifecycle的使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
超詳細講解SpringCloud?Commons公共抽象的用法
這篇文章主要介紹了超詳細講解SpringCloud?Commons公共抽象的用法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
java使用Runtime執(zhí)行系統(tǒng)命令遇到的問題
這篇文章主要介紹了java使用Runtime執(zhí)行系統(tǒng)命令遇到的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
ShardingSphere jdbc集成多數(shù)據(jù)源的實現(xiàn)步驟
本文主要介紹了ShardingSphere jdbc集成多數(shù)據(jù)源的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10
SpringSecurity的TokenStore四種實現(xiàn)方式小結(jié)
本文主要介紹了SpringSecurity的TokenStore四種實現(xiàn)方式小結(jié),分別是InMemoryTokenStore,JdbcTokenStore,JwkTokenStore,RedisTokenStore,具有一定的參考價值,感興趣的可以了解一下2024-01-01

