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(sparkKafkaStreamExecutor);
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);
}

}

到此,逻辑流程实现完毕,谢谢阅读。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值