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

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

实现方法有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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

友情链接更多精彩内容