- 有一些特殊的任务需要在系统启动时执行,例如配置文件的加载、数据库初始化等操作。
如果不使用Spring Boot,可以使用Listener解决。
- Spring Boot 对此提供了两种解决方案,CommandLineRunner和ApplicationRunner。
CommandLineRunner和ApplicationRunner基本一致,差别主要体现在参数上
1 、CommandLineRunner
Spring Boot 项目在启动时会遍历所有CommandLineRunner的实现类并调用其中的run方法,如果整个系统中有多个CommandLineRunner的实现类,那么可以使用@Order注解对这些实现类的调用顺序进行排序。
@Component@Order(1)@Slf4jpublic class MyCommandLineRunner1 implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {log.info("Runner1>>>"+ Arrays.toString(args));}}@Component@Order(2)@Slf4jpublic class MyCommandLineRunner2 implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {log.info("Runner2>>>"+ Arrays.toString(args));}}
代码说明:
@Order(2)注解来描述CommandLineRunner的执行顺序,数字越小越先执行。
Run 方法中是调用的核心逻辑,参数是系统启动时传入的参数,即入口类中main方法的参数。
2 、ApplicationRunner
ApplicationRunner的用法和CommandLineRunner基本一致,区别只要体现在run方法的参数上。
@Component@Order(1)@Slf4jpublic class MyApplicationRunner1 implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {List<String> nonOptionArgs=args.getNonOptionArgs();System.out.println("runner1-主方法的参数args:"+nonOptionArgs);//getOptionNames()获取主函数参数中的键值对的所有键集合Set<String> optionNames=args.getOptionNames();for(String optionName:optionNames){//getOptionValues(optionName)通过键获取值System.out.println("runner1,key:"+optionName+";value="+args.getOptionValues(optionName));}}}
@Component@Order(2)@Slf4jpublic class MyApplicationRunner2 implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {List<String> nonOptionArgs=args.getNonOptionArgs();System.out.println("runner2-主方法的参数args:"+nonOptionArgs);Set<String> optionNames=args.getOptionNames();for(String optionName:optionNames){System.out.println("runner2,key:"+optionNames+";value="+args.getOptionValues(optionName));}}}
代码说明:
@Order注解依然是用来描述执行顺序的,数字越小越优先执行。
Run方法的参数是ApplicationArguments对象,如果想从ApplicationArguments对象中获取入口类中main方法接收的参数,调用ApplicationArguments的getNonOptionArgs即可,
ApplicationArguments中的getOptionNames方法用来获取项目启动命令行中参数的key
使用下面命令测试:
java -jar ***.jar --name=guanyu --age=20 西游记 吴承恩
