1 protected void afterRefresh(ConfigurableApplicationContext context, 2 ApplicationArguments args) { 3 callRunners(context, args); 4 } 5 6 private void callRunners(ApplicationContext context, ApplicationArguments args) { 7 List<Object> runners = new ArrayList<Object>(); 8 runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); 9 runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); 10 AnnotationAwareOrderComparator.sort(runners); 11 for (Object runner : new LinkedHashSet<Object>(runners)) { 12 if (runner instanceof ApplicationRunner) { 13 callRunner((ApplicationRunner) runner, args); 14 } 15 if (runner instanceof CommandLineRunner) { 16 callRunner((CommandLineRunner) runner, args); 17 } 18 } 19 } 20 21 private void callRunner(ApplicationRunner runner, ApplicationArguments args) { 22 try { 23 (runner).run(args); 24 } 25 catch (Exception ex) { 26 throw new IllegalStateException("Failed to execute ApplicationRunner", ex); 27 } 28 }
上下文刷新结束后,可以实现ApplicationRunner或者CommandLineRunner接口来实现上下文成功初始化后的一些操作。
最终调用
1 listeners.finished(context, null);
通知所有监听器,上下文初始化结束。
applicationrunner commandlinerunner两种runner除了参数类型不一样,其他的没有区别,执行顺序也是一起排序使用order控制。使用的排序规则是AnnotationAwareOrderComparator。