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)在下面场景下被调用:

  1. 程序正常退出;
  2. 使用System.exit();
  3. 终端使用Ctrl+C触发的中断;
    4)系统关闭;
    5)OutOfMemory宕机;
  4. 使用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销毁前执行的一个线程.当然这个线程依然要自己写.

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐