CommandLineRunner和ApplicationRunner

Spring boot會在上下問初始化後,調用所有的Runner 。

主要接口

public interface CommandLineRunner {
    void run(String... args) throws Exception;
}
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

只要參數不同,在使用的時候我們只需根據需求實現任意一個接口即可

package cn.huanuo;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(args);
    }
}

執行順序,如果實現了多個Runner 可以使用@Order 執行執行順序,Spring boot 在遍歷所有的Runner後會進行排序處理。

測試結果

image.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章