springboot的ApplicationRunner和CommandLineRunner

當咱們但願在springboot容器後,執行一些操做的時候,咱們能夠考慮使用ApplicationRunner或者CommandLineRunnerjava

問題:spring

  1. ApplicationRunner與CommandLineRunner誰先執行
  2. 二者的區別在哪
  3. 多個CommandLineRunner 執行順序問題

1.ApplicationRunner與CommandLineRunner誰先執行。

咱們在一個應用中分別實現兩個接口數組

@Component
    public class CommandLineRunnerTest implements CommandLineRunner {

	@Override
	public void run(String... arg0) throws Exception {
		System.out.println("CommandLineRunner=====執行開始");
		    for (int i = 0; i < arg0.length; i++) {
			    System.out.println(arg0[i]);
		    }
		System.out.println("CommandLineRunner=====執行完畢");

	    }

    }
複製代碼
@Component
    public class ApplicationRunnerTest implements ApplicationRunner {
    
    	@Override
    	public void run(ApplicationArguments arg0) throws Exception {
    		System.out.println("ApplicationRunner=====執行開始");
    		System.out.println(arg0.getNonOptionArgs());
    		System.out.println(arg0.getOptionNames());
    		System.out.println("ApplicationRunner=====執行完成");
    
    	}
    
    }
複製代碼

從執行結果來看,ApplicationRunner默認先於CommandLineRunner執行springboot

ApplicationRunner=====執行開始
    []
    [name, age]
    [lisi]
    ApplicationRunner=====執行完成
    CommandLineRunner=====執行開始
    --name=lisi
    --age=12
    CommandLineRunner=====執行完畢
複製代碼

2.二者的區別,以及與main方法的聯繫

兩個接口中都有run方法,負責接收來自應用外部的參數,ApplicationRunner的run方法會將外部參數封裝成一個ApplicationArguments對象,而CommandLineRunner接口中run方法的參數則爲String數組。eclipse

咱們再回頭看看main方法ide

@SpringBootApplication
    public class AliyunmqApplication {
    
    	public static void main(String[] args) {
    		System.out.println("main方法==========執行開始");
    		for (int i = 0; i < args.length; i++) {			
    			System.out.println(args[i]);			
    		}
    		System.out.println("main方法==========執行完畢");
    		SpringApplication.run(AliyunmqApplication.class, args);
    	}
    }
複製代碼

咱們看到main方法也是接收一個args 數組參數。spa

執行發現:code

main方法==========執行開始
    --name=lisi
    --age=12
    main方法==========執行完畢
    ..............
    ..............
    ApplicationRunner=====執行開始
    []
    [name, age]
    [lisi]
    ApplicationRunner=====執行完成
    CommandLineRunner=====執行開始
    --name=lisi
    --age=12
    CommandLineRunner=====執行完畢
複製代碼

main方法的arg參數 和 CommandLineRunner方法的arg數組的值是同樣的。cdn

總的來看: ApplicationRunner run方法中的ApplicationArguments 對象,對輸入參數作了封裝,讓咱們能夠使用 get**()的形式獲取參數。CommandLineRunner run方法的arg數組則是原裝。對象

以eclipse爲例看參數設置:

3. 多個實現類的執行順序

兩種方法

  • 使用@Order(value=整數值)
  • 實現Ordered接口,在方法裏return 一個順序值
相關文章
相關標籤/搜索