springboot啟動后和停止前執(zhí)行方法示例詳解
springboot啟動后即執(zhí)行的方法
1)實現(xiàn)ApplicationRunner接口
@Configuration
public class ApplicationService implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
iForwardQueuesService.create();
}
}2)實現(xiàn)CommandLineRunner接口
@Configuration
public class ApplicationService implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("執(zhí)行平臺登出");
}
}注意:如果ApplicationListener和CommandLineRunner同時存在,則ApplicationRunner接口先執(zhí)行,CommandLineRunner后執(zhí)行;
也可以使用執(zhí)行執(zhí)行順序
@Configuration
@Order(1)
public class ApplicationService implements CommandLineRunner {
}原理:
SpringApplication 的run方法會執(zhí)行afterRefresh方法。
afterRefresh方法會執(zhí)行callRunners方法。
callRunners方法會調用所有實現(xiàn)ApplicationRunner和CommondLineRunner接口的方法。
springboot停止前執(zhí)行的方法
1)實現(xiàn)DisposableBean接口并實現(xiàn)destroy方法
springboot銷毀時執(zhí)行
@Configuration
public class ApplicationService implements DisposableBean,{
@Override
public void destroy() throws Exception {
log.info("執(zhí)行平臺登出");
platformService.PlatformLogout();
}
}2)使用ShutdownHook關閉鉤子
JAVA虛擬機關閉鉤子(Shutdown Hook)在下面場景下被調用:
- 程序正常退出;
- 使用System.exit();
- 終端使用Ctrl+C觸發(fā)的中斷;
4)系統(tǒng)關閉;
5)OutOfMemory宕機;使用Kill pid命令干掉進程(注:在使用kill -9 pid時,是不會被調用的);
@SpringBootApplication
@ComponentScan(value = "com.xxxxxx")
public class ForwardGbApplication {
public static void main(String[] args) {
ForwardGbApplication application=new ForwardGbApplication();
Thread t = new Thread(new ShutdownHook(application), "ShutdownHook-Thread");
Runtime.getRuntime().addShutdownHook(t);
SpringApplication.run(ForwardGbApplication.class, args);
}
static class ShutdownHook implements Runnable{
private ForwardGbApplication manager;
public ShutdownHook(ForwardGbApplication serverManager){
manager = serverManager;
}
@Override
public void run() {
try {
PlatformService platform = ApplicationContextHandle.getObject(PlatformService.class);
platform.PlatformLogout();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
RunTime.getRunTime().addShutdownHook的作用就是在JVM銷毀前執(zhí)行的一個線程.當然這個線程依然要自己寫.
到此這篇關于springboot啟動后和停止前執(zhí)行方法的文章就介紹到這了,更多相關springboot啟動執(zhí)行方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JAVA解決在@autowired,@Resource注入為null的情況
這篇文章主要介紹了JAVA解決在@autowired,@Resource注入為null的情況,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10
SpringBoot Controller接收參數(shù)的幾種常用方式
這篇文章主要介紹了SpringBoot Controller接收參數(shù)的幾種常用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
Java+ElasticSearch+Pytorch實現(xiàn)以圖搜圖功能
這篇文章主要為大家詳細介紹了Java如何利用ElasticSearch和Pytorch實現(xiàn)以圖搜圖功能,文中的示例代碼講解詳細,具有一定的學習價值,感興趣的小伙伴可以了解一下2023-06-06

