亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot 在項目啟動之后執(zhí)行自定義方法的兩種方式小結(jié)

 更新時間:2021年09月18日 11:52:38   作者:Nick  
這篇文章主要介紹了SpringBoot 在項目啟動之后執(zhí)行自定義方法的兩種方式小結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

SpringBoot 項目啟動之后執(zhí)行自定義方法的兩種方式

在測試配置中心的配置時,想在項目啟動成功之后打印配置項,然后需要執(zhí)行自定義的類

一般項目中也會在這個地方進行初始化數(shù)據(jù)的一些操作

方式一 實現(xiàn) CommandLineRunner 接口

自定義類并實現(xiàn) CommandLineRunner 接口,實現(xiàn)run()方法,需要執(zhí)行的語句就放在 run() 方法中

例:

@Component
@Order(1)  // 控制類執(zhí)行的順序越小越靠前
public class StartInitializer implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("項目啟動,執(zhí)行 CommandLineRunner 實現(xiàn)類的方法");
    }
}

方式二 實現(xiàn) ApplicationRunner 接口

自定義類并實現(xiàn) ApplicationRunner 接口,實現(xiàn)run()方法,需要執(zhí)行的語句就放在 run() 方法中

例:

@Component
@Order(2) // 控制類執(zhí)行的順序越小越靠前
public class AppInitializer implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("項目啟動,執(zhí)行 ApplicationRunner 實現(xiàn)類的方法");
    }
}

二者區(qū)別

區(qū)別在于實現(xiàn)方法 run() 中的參數(shù)類型不一樣

實現(xiàn) ApplicationRunner 接口的 run() 方法參數(shù)類型為: ApplicationArguments

實現(xiàn) CommandLineRunner 接口的 run() 方法參數(shù)類型為: String...

實現(xiàn)效果

Springboot 項目啟動后執(zhí)行某些自定義代碼

Springboot給我們提供了兩種“開機啟動”某些方法的方式:ApplicationRunner和CommandLineRunner。

這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執(zhí)行某些方法。我們可以通過實現(xiàn)ApplicationRunner和CommandLineRunner,來實現(xiàn),他們都是在SpringApplication 執(zhí)行之后開始執(zhí)行的。

CommandLineRunner接口可以用來接收字符串數(shù)組的命令行參數(shù),ApplicationRunner 是使用ApplicationArguments 用來接收參數(shù)的

代碼示例

@Component//被spring容器管理
@Order(1)//如果多個自定義ApplicationRunner,用來標明執(zhí)行順序
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("-------------->" + "項目啟動,now=" + new Date());
        myTimer();
    }
    public static void myTimer(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("------定時任務(wù)--------");
            }
        }, 0, 1000);
    }
}

執(zhí)行結(jié)果

2018-02-08 14:10:16.490  INFO 10236 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)
-------------->項目啟動,now=Thu Feb 08 14:10:16 CST 2018
------定時任務(wù)--------
2018-02-08 14:10:16.497  INFO 10236 --- [           main] com.mlxs.springboot01.web.MainApp        : Started MainApp in 5.595 seconds (JVM running for 6.334)
------定時任務(wù)--------
------定時任務(wù)--------
------定時任務(wù)--------
------定時任務(wù)--------
------定時任務(wù)--------
------定時任務(wù)--------

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論