springboot CommandLineRunner接口和ApplicationRunner接口,ApplicationListener
springboot 容器启动后,有时需要执行一些初始化操作,比如将数据初始化到内存。
ApplicationListener 示例
1 @Component 2 public class InitApplicationListener implements ApplicationListener<ContextRefreshedEvent> { 3 4 @Autowired 5 private DataManager dataManager; 6 7 public void onApplicationEvent(ContextRefreshedEvent event) { 8 if (event.getApplicationContext().getParent() == null) { 9 try { 10 // 初始化搜索支持数据 11 dataManager.init(); 12 } catch (Exception e) { 13 throw new RuntimeException(e); 14 } 15 } 16 } 17 18 }
CommandLineRunner 示例
1 @Component 2 @Order(value=1) 3 public class MyStartupRunner1 implements CommandLineRunner { 4 5 public void run(String... args) throws Exception { 6 System.out.println(">>>>>>>>>>>>>>>服务启动执行1,执行加载数据等操作<<<<<<<<<<<<<"); 7 } 8 9 }
@Component @Order(value=2) public class MyStartupRunner2 implements CommandLineRunner { public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服务启动执行2,执行加载数据等操作<<<<<<<<<<<<<"); } }
执行日志如下:
[ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8888 (http)
>>>>>>>>>>>>>>>服务启动执行1,执行加载数据等操作<<<<<<<<<<<<<
>>>>>>>>>>>>>>>服务启动执行2,执行加载数据等操作<<<<<<<<<<<<<
ApplicationRunner 示例
1 @Component 2 public class MyApplicationRunner implements ApplicationRunner{ 3 @Override 4 public void run(ApplicationArguments args) throws Exception { 5 System.out.println(Arrays.asList(args.getSourceArgs())); 6 System.out.println("测试ApplicationRunner接口"); 7 } 8 }
执行日志如下:
>>>>>>>>>>>>>>>服务启动执行1,执行加载数据等操作<<<<<<<<<<<<<
>>>>>>>>>>>>>>>服务启动执行2,执行加载数据等操作<<<<<<<<<<<<<
[测试测试, 接口测试]
测试ApplicationRunner接口
@Order注解
如果有多个实现类,而你需要他们按一定顺序执行的话,可以在实现类上加上@Order注解。@Order(value=整数值)。SpringBoot会按照@Order中的value值从小到大依次执行。
Tips
如果你发现你的实现类没有按照你的需求执行,请看一下实现类上是否添加了Spring管理的注解(@Component)。
浙公网安备 33010602011771号