想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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM