转载

【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"/>

原文  https://segmentfault.com/a/1190000021130769
正文到此结束
Loading...