您的位置:首页 > 编程语言 > Java开发

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

2018-02-09 16:25 573 查看
常有在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);
}

}
到此,逻辑流程实现完毕,谢谢阅读。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: