08、SpringBoot中的ApplicationRunner和CommandLineRunner

1、應用場景

有時我們需要在應用程序啟動時,執(zhí)行一些初始化操作,類似@PostContruct注解的作用!如讀取配置文件,加載數(shù)據(jù)至緩存,清除緩存等操作。SpringBoot為我們提供了ApplicationRunner和CommandLineRunner接口。當接口有多個實現(xiàn)類時,提供了@Order注解實現(xiàn)自定義執(zhí)行順序,也可以實現(xiàn)Order接口來定義順序。(數(shù)字越小優(yōu)先級越高,即優(yōu)先執(zhí)行)
ApplicationRunner中run方法的參數(shù)為ApplicationArguments,而CommandLineRunner接口中run方法的參數(shù)為String數(shù)組。想要更詳細地獲取命令行參數(shù),那就使用ApplicationRunner接口

2、ApplicationRunner接口

@Component
@Order(2)
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("MyApplicationRunner 執(zhí)行了..."+ JSON.toJSONString(args.getSourceArgs()));
    }
}

3、CommandLineRunner接口

@Component
@Order(1)
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner 執(zhí)行了..." + JSON.toJSONString(args));
    }
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容