1、應用場景
有時我們需要在應用程序啟動時,執(zhí)行一些初始化操作,類似@PostContruct注解的作用!如讀取配置文件,加載數(shù)據(jù)至緩存,清除緩存等操作。SpringBoot為我們提供了ApplicationRunner和CommandLineRunner接口。當接口有多個實現(xiàn)類時,提供了@Order注解實現(xiàn)自定義執(zhí)行順序,也可以實現(xiàn)Order接口來定義順序。(數(shù)字越小優(yōu)先級越高,即優(yōu)先執(zhí)行)
ApplicationRunner中run方法的參數(shù)為ApplicationArguments,而CommandLineRunner接口中run方法的參數(shù)為String數(shù)組。想要更詳細地獲取命令行參數(shù),那就使用ApplicationRunner接口
2、ApplicationRunner接口
@Component
@Order(2)
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("MyApplicationRunner 執(zhí)行了..."+ JSON.toJSONString(args.getSourceArgs()));
}
}
3、CommandLineRunner接口
@Component
@Order(1)
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("MyCommandLineRunner 執(zhí)行了..." + JSON.toJSONString(args));
}
}