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接口的方法。
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)在下面场景下被调用:
@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销毁前执行的一个线程.当然这个线程依然要自己写.