工作中或多或少有这样的需求,就是在项目启动后执行某个操作,一般来说listener可以满足这样的需求。但当遇到需要注入在spring容器的bean时,listener就不能满足了。这时候我们需要使用ApplicationRunner或者CommandLineRunner。这边先说个结论,用ApplicationRunner比CommandLineRunner好。
(一)ApplicationRunner
@Component public class MyFirstApplicationRunner implements ApplicationRunner, Ordered { @Autowired PeopleVo peopleVo; @Override public void run(ApplicationArguments applicationArguments) throws Exception { System.out.println("MyFirstApplicationRunner start"); System.out.println("获取到的参数: " + applicationArguments.getOptionNames()); System.out.println("获取到的参数: " + applicationArguments.getNonOptionArgs()); System.out.println("获取到的参数: " + applicationArguments.getOptionValues("name")); for (String str : applicationArguments.getSourceArgs()) { System.out.println("获取到的参数: " + str); } System.out.println(peopleVo); } @Override public int getOrder() { return 0; } }
启动项配置
项目启动后的输出
2019-04-16 22:00:45.375 INFO 50401 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2019-04-16 22:00:45.431 INFO 50401 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) MyFirstApplicationRunner start 命令行的keys: [name, age] 非命令行的参数值: [bbbbb, cccc] 指定命令行key名称的值: [abc] 获取到的参数: --name=abc 获取到的参数: bbbbb 获取到的参数: cccc 获取到的参数: --age=19 PeopleVo(name=vincent, age=10)
(二)CommandLineRunner
@Component @Order(2) public class MyFirstCommandLineRunner implements CommandLineRunner { @Override public void run(String... strings) throws Exception { System.out.println("MyFirstCommandLineRunner start"); for(String str : strings){ System.out.println(str); } } }
启动项配置还如上。
输入结果如下:
MyFirstCommandLineRunner start --name=abc bbbbb cccc --age=19
(三)Ordered接口和@Order注解
Ordered接口和@Order注解的作用就是限定多个实现了ApplicationRunner或者CommandLineRunner的类的执行顺序
总结
ApplicationRunner和CommandLineRunner的作用几乎相同,而且ApplicationRunner的作用比CommandLineRunner好些。