【Spring】如何在Spring容器启动完成之后开始一个任务?
文章目录
在某些情况下,我们的任务需要在Spring启动完成之后再执行相关的任务。总共两步骤:
1,实现ApplicationListener<ContextRefreshedEvent>接口,并重写onApplicationEvent(ContextRefreshedEvent contextRefresh)方式实现业务逻辑
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class Task implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
System.out.println("do something...");
}
}
2,在Spring配置文件中加入这个Bean
<bean id="Task" class="Task"/>
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论