背景
因为需要保证所有调度相关的依赖注入spring容器才创建所以定时调度任务,所以需要实现在Spring容器将所有的Bean都初始化完成之后才自动执行一次执行方法(创建一个调度任务)
实现
实现ApplicationListener接口,并实现 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法
@Service
public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
if (contextRefreshedEvent.getApplicationContext().getParent().getParent() == null) {//保证只执行一次
//需要执行的方法
}
}
}
至于为什么先做判断,因为Spring存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理