这篇文章主要介绍了springboot启动后和停止前执行方法,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
springboot启动后即执行的方法
1)实现ApplicationRunner接口
@Configuration
public class ApplicationService implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
iForwardQueuesService.create();
}
}
2)实现CommandLineRunner接口
@Configuration
public class ApplicationService implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("执行平台登出");
}
}
注意:如果ApplicationListener和CommandLineRunner同时存在,则ApplicationRunner接口先执行,CommandLineRunner后执行;
也可以使用执行执行顺序
@Configuration
@Order(1)
public class ApplicationService implements CommandLineRunner {
}
原理:
SpringApplication 的run方法会执行afterRefresh方法。
afterRefresh方法会执行callRunners方法。
callRunners方法会调用所有实现ApplicationRunner和CommondLineRunner接口的方法。
springboot停止前执行的方法
1)实现DisposableBean接口并实现destroy方法
springboot销毁时执行
@Configuration
public class ApplicationService implements DisposableBean,{
@Override
public void destroy() throws Exception {
log.info("执行平台登出");
platformService.PlatformLogout();
}
}
2)使用ShutdownHook关闭钩子
JAVA虚拟机关闭钩子(Shutdown Hook)在下面场景下被调用:
- 程序正常退出;
- 使用System.exit();
- 终端使用Ctrl+C触发的中断;
4)系统关闭;
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销毁前执行的一个线程.当然这个线程依然要自己写.
到此这篇关于springboot启动后和停止前执行方法的文章就介绍到这了,更多相关springboot启动执行方法内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:springboot启动后和停止前执行方法示例详解
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- Java中的日期时间处理及格式化处理 2023-04-18
- JSP页面间传值问题实例简析 2023-08-03
- JSP 制作验证码的实例详解 2023-07-30
- Java实现顺序表的操作详解 2023-05-19
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- 深入了解Spring的事务传播机制 2023-06-02