Runner使用
如果需要在SpringApplication启动后执行一些逻辑,可以使用ApplicationRunner或CommandLineRunner接口,这两个接口都是只有一个run方法
1 2 3 4 5
| public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
|
1 2 3 4 5 6
| public interface CommandLineRunner {
void run(String... args) throws Exception;
}
|
实现
1 2 3 4 5 6 7
| @Component public class CodeReview implements ApplicationRunner {
@Override public void run(ApplicationArguments args) throws Exception { }
|
执行位置
该实现类是在SpringApplication.run方法最后进行执行的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| afterRefresh(context, applicationArguments);
protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) { callRunners(context, args); }
private void callRunners(ApplicationContext context, ApplicationArguments args) { List<Object> runners = new ArrayList<Object>(); runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); AnnotationAwareOrderComparator.sort(runners); for (Object runner : new LinkedHashSet<Object>(runners)) { if (runner instanceof ApplicationRunner) { callRunner((ApplicationRunner) runner, args); } if (runner instanceof CommandLineRunner) { callRunner((CommandLineRunner) runner, args); } } }
|