Runner使用
如果需要在SpringApplication启动后执行一些逻辑,可以使用ApplicationRunner或CommandLineRunner接口,这两个接口都是只有一个run方法
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
实现
@Component
public class CodeReview implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// 业务逻辑
}
执行位置
该实现类是在SpringApplication.run方法最后进行执行的
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);
}
}
}
本文由 mdnice 多平台发布