SpringBoot实现多个ApplicationRunner时部分接口未执行
在spring的项目中,需要在容器启动之后执行一些操作。spring提供了ApplicationRunner和CommandLineRunner两个接口可以帮助我们实现这种需求。当项目中实现了多个ApplicationRunner接口,并且其中一个使用了类似于while(true)这样不会推出的循环体。将会导致后续的ApplicationRunner接口不会被调用。如下:@Compo...
·
在springboot的项目中,需要在容器启动之后执行一些操作。springboot提供了ApplicationRunner和CommandLineRunner两个接口可以帮助我们实现这种需求。
当项目中实现了多个ApplicationRunner接口,并且其中一个使用了类似于while(true)这样不会退出的循环体。将会导致后续的ApplicationRunner接口不会被调用。
如下:
@Component
@Slf4j
public class RunnerTest1 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
while (true) {
System.out.println("this is RunnerTest1");
Thread.sleep(100);
}
}
}
@Component
@Slf4j
public class RunnerTest2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
while (true) {
System.out.println("this is RunnerTest2");
Thread.sleep(100);
}
}
}
输出结果:
可以看到项目启动后RunnerTest2 将不会被执行。
通过分析springboot启动的源码可以发现,在applicationContext容器加载完成之后,会调用SpringApplication类的callRunners方法
该方法中会获取所有实现了ApplicationRunner和CommandLineRunner的接口bean,然后依次执行对应的run方法,并且是在同一个线程中执行。因此如果有某个实现了ApplicationRunner接口的bean的run方法一直循环不返回的话,后续的代码将不会被执行。
更多推荐
已为社区贡献1条内容
所有评论(0)