spring boot, 容器启动后执行某操作


常有在spring容器启动后执行某些操作的需求,现做了一个demo的实现,做一下记录,也希望可以给需要的同学提供参考。

1.spring启动后,以新线程执行后续需要的操作,所以执行类实现Runnable接口

@Component

public class StepExecutor implements Runnable{

     @Override
public void run() {
startStreamTask();

}

        public void startStreamTask() {

                //do your business

        }

}

2.监听类实现ApplicationListener<ContextRefreshedEvent> 

/**
 * spring boot 容器加载完成后执行
 * @author yhz
 *
 */
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext ac = event.getApplicationContext();
StepExecutor StepExecutor = ac.getBean(StepExecutor .class);
Thread thread = new Thread(StepExecutor);
thread.start();
}

}

注:亲测,spring boot项目下,上面方式正确触发执行一次;如果是spring web项目下,可能会造成二次执行,因为此时系统会存在两个容器,一个是spring本身的root application context,另一个是servlet容器(作为spring容器的子容器,projectName-servlet context),此时,加以下限制条件规避:

               if(event.getApplicationContext().getParent()==null){   

                        //只有root application context 没有父容器

                        //start the executor

                }

3.容器启动时注册监听类

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(DemoApplication .class);
springApplication.addListeners(new ApplicationStartup());
springApplication.run(args);
}

}

到此,逻辑流程实现完毕,谢谢阅读。
————————————————
版权声明:本文为CSDN博主「river_rock」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/swjtu_yhz/article/details/79299749

原文地址:https://www.cnblogs.com/renjiaqi/p/11834565.html