概述
CommandLineRunner和ApplicationRunner是Spring Boot所提供的接口删壮,他們都有一個run()方法掏缎。所有實現(xiàn)他們的Bean都會在Spring Boot服務啟動之后自動地被調(diào)用。且經(jīng)測試蒙谓,ApplicationRunner的加載優(yōu)先于CommandlineRunner.由于這個特性柜候,它們是一個理想地方去做一些初始化的工作,或者寫一些測試代碼汽摹。
使用方式:讓初始化類實現(xiàn)這兩個接口的run()方法,同時將這兩個類交給Spring容器管理苦锨。
CommandLineRunner
@Component
public class Init implements CommandLineRunner {
? ? @Override
? ? public void run(String... args) throws Exception {
? ? ? ? String className = this.getClass().getName();
? ? ? ? System.out.println("使用" + className + "初始化配置...");
? ? ? ? System.out.println(Arrays.toString(args));
? ? ? ? System.out.println("使用" + className + "初始化結束...");
? ? }
}
————————————————
加一個虛擬機啟動參數(shù)
啟動查看
這種場景在服務器上特別常用逼泣。比如我們想執(zhí)行某個操作,又不想對外部暴露舟舒,此時可以使用CommandLineRunner作為該操作的入口拉庶。
ApplicationRunner
ApplicationRunner與CommandLineRunner做的事情是一樣的,也是在服務啟動之后其run()方法會被自動地調(diào)用秃励,唯一不同的是ApplicationRunner會封裝命令行參數(shù)砍的,可以很方便地獲取到命令行參數(shù)和參數(shù)值。
@Component
public class Init2 implements ApplicationRunner {
? ? @Override
? ? public void run(ApplicationArguments args) throws Exception {
? ? ? ? String className = this.getClass().getName();
? ? ? ? System.out.println("使用" + className + "初始化配置...");
? ? ? ? System.out.println(args.getOptionValues("param"));
? ? ? ? System.out.println("使用" + className + "初始化結束...");
? ? }
}
執(zhí)行結果:
我們可以發(fā)現(xiàn)莺治,通過run()方法的參數(shù)ApplicationArguments可以很方便地獲取到命令行參數(shù)的值。
所以如果你的工程需要獲取命令行參數(shù)的話帚稠,建議你使用ApplicationRunner谣旁。