springboot启动后和停止前执行方法示例详解

这篇文章主要介绍了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启动执行方法内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是springboot启动后和停止前执行方法示例详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java