欢迎大家关注我公众号“从零开始的it转行生”

想springboot启动完成后执行某个方法

如题,很多时候,我们都需要在springboot项目启动后初始化化一些自己的数据

原文地址:https://www.jianshu.com/p/f80f833ab8f6
实现方法有2个。
一、ApplicationRunner
实现ApplicationRunner接口
打上@Component+implements ApplicationRunner

@Component
public class DemoApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner");
    }
}

二、CommandLineRunner
实现CommandLineRunner接口
打上@Component+implements CommandLineRunner

@Component
public class DemoComLiner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner");
    }
}

原理讲解

SpringApplication的run方法会执行afterRefresh方法
SpringApplication

afterRefresh会触发callRunners方法
afterRefresh

callRunners方法会调用容器里面所有实现了ApplicationRunner、CommandLineRunner接口的方法
callRunners

posted @ 2020-07-15 16:36  大佬健  阅读(2724)  评论(0编辑  收藏  举报

欢迎大家关注我公众号“从零开始的it转行生”