在項目中有時需要在項目啟動之后進行預加載數據(例如配置在數據中的常量數據),這是可以使用spring boot 提供的CommandLineRunner接口
新建類實現CommandLineRunner接口,同時使用 @Component 注解
@Component @Order(1) public class ConstantPreloading implements CommandLineRunner{ private static final Logger LOGGER = LoggerFactory.getLogger(ConstantPreloading.class); @Override public void run(String... args) throws Exception { LOGGER.info("=========預加載一些常量信息=========="); } }
1、如果項目中需要多個預加載的動作,可以新建多個類並且實現CommandLineRunner接口,spring boot會自動掃描實現了CommandLineRunner接口的bean並依次執行。
2、如果多個runner需要按優先級執行,這是可以使用@Order 注解,通過源碼查看,order的值越小優先級越高(源碼處排序方法 AnnotationAwareOrderComparator.sort(runners))。
runner是由org.springframework.boot.SpringApplication.callRunners(ApplicationContext, ApplicationArguments) 執行的,部分代碼如下
private void callRunners(ApplicationContext context, ApplicationArguments args) { List<Object> runners = new ArrayList<>(); runners.addAll(context.getBeansOfType(ApplicationRunner.class).values()); runners.addAll(context.getBeansOfType(CommandLineRunner.class).values()); AnnotationAwareOrderComparator.sort(runners); for (Object runner : new LinkedHashSet<>(runners)) { if (runner instanceof ApplicationRunner) { callRunner((ApplicationRunner) runner, args); } if (runner instanceof CommandLineRunner) { callRunner((CommandLineRunner) runner, args); } } }
