spring启动后自动执行一次方法:因为需要保证所有调度相关的依赖注入spring容器才创建所以定时调度任务,所以需要实现在Spring容器将所有的Bean都初始化完成之后才自动执行一次执行方法(创建一个调度任务)。
SpringBoot的ApplicationRunner
springBoot提供了两种接口CommandLineRunner和ApplicationRunner,是在容器启动完成时执行,选择一个接口实现即可。
@Component public class InitScheduleJobRunner implements ApplicationRunner { //ApplicationRunner中run方法的参数为ApplicationArguments @Override public void run(ApplicationArguments args) throws Exception { //todo 执行一次 } } @Component public class InitSchedule2JobRunner implements CommandLineRunner { //CommandLineRunner接口中run方法的参数为String数组 @Override public void run(String... args) throws Exception { //todo 执行一次 } }ApplicationListener< ContextRefreshedEvent>
@Service public class InitScheduleJobService implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { root application context 没有parent,他就是老大. if (event.getApplicationContext().getParent() == null) { //todo 执行一次 需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法 } } }先做判断,因为Spring存在两个容器,一个是root application context ,另一个是 projectName-servlet context(作为root application context的子容器)。这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理。