Springboot 項目啓動後執行某些自定義代碼

Springboot 項目啓動後執行某些自定義代碼

Springboot給咱們提供了兩種「開機啓動」某些方法的方式:ApplicationRunner和CommandLineRunner。

這兩種方法提供的目的是爲了知足,在項目啓動的時候馬上執行某些方法。咱們能夠經過實現ApplicationRunner和CommandLineRunner,來實現,他們都是在SpringApplication 執行以後開始執行的。

CommandLineRunner接口能夠用來接收字符串數組的命令行參數,ApplicationRunner 是使用ApplicationArguments 用來接收參數的

代碼示例

@Component//被spring容器管理
@Order(1)//若是多個自定義ApplicationRunner,用來標明執行順序
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("------定時任務--------");
            }
        }, 0, 1000);
    }
}

執行結果

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
------定時任務--------
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)
------定時任務--------
------定時任務--------
------定時任務--------
------定時任務--------
------定時任務--------
------定時任務--------
相關文章
相關標籤/搜索