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 {@Overridepublic 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);}}}
https://zhhll.icu/2022/框架/springboot/基础/16.Runner使用/
本文由mdnice多平台发布