一)ApplicationRunner或CommandLineRunner簡介
當SpringBoot啓動之後,如需執行一些特定的代碼,這兩個接口以相同的方式工作,並提供一個單一的run方法,該方法在SpringApplication.run(…)完成之前就被調用。
比如說,預先加載一些配置,註冊一些bean等等。
二)CommandLineRunner
該接口只提供了run方法,並且入參是String類型。
@Component:此註解把該類聲明成一個bean。
@Order:當有多個類繼承了CommandLineRunner接口,可指定執行的順序。
package com.oysept.config;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value=1)
public class FirstCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner, 1111" + args);
}
}
三)ApplicationRunner
該接口只提供了run方法,並且入參是ApplicationArguments對象類型。
@Component:此註解把該類聲明成一個bean。
@Order:當有多個類繼承了CommandLineRunner接口,可指定執行的順序。
package com.oysept.config;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value=2)
public class FirstApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner, 2222" + args);
}
}
四)區別
1、兩個接口run方法,入參不同,ApplicationRunner.run()入參是ApplicationArguments對象類型,CommandLineRunner.run入參是String類型。
2、ApplicationArguments參數已包含String的參數。也就是說,當只需要String類型入參時,繼承CommandLineRunner即可。當入參需多樣化時,可繼承ApplicationRunner接口。
識別二維碼關注個人微信公衆號
本章完結,待續,歡迎轉載!
本文說明:該文章屬於原創,如需轉載,請標明文章轉載來源!