首页 > 解决方案 > Spring Boot 多个 CommandLineRunner 执行顺序和状态

问题描述

我有一些启动操作要一个接一个地执行。这两个运行器都执行一些繁重的数据库操作。

@Slf4j
@Data
@Component
@Order(1)
public class MyFailureHandlerA implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        some_io_calls_a();
    }

}
@Slf4j
@Data
@Component
@Order(2)
public class MyFailureHandlerB implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        some_io_calls_b();
    }

}

我需要确保@Order(2)runner 仅在@Order(1)完成处理后才开始。

有什么方法可以实现这一点,比如将跑步者注册到一些策略上,以便监控他们的完成情况。

我找到了一种方法,例如,我可以等到单例作用域 bean 变量的值变为 true,它仅在第一个运行者完成它的任务时设置。但我担心这是否被推荐。

或者,我可以依靠@DependsOn来完成任务吗?是否可以保证,通过使用@DependsOn("MyFailureHandlerA")overMyFailureHandlerB将保证 1st runner 完成了它的全部操作?

我尝试的另一种方法是,从一个运行器一个接一个地调用服务,如下所示:

@Slf4j
@Data
@Component
public class MyFailureHandler implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        some_io_calls_q();
        some_io_calls_b();
    }

}

这是否有意义并且会确保操作一个接一个地执行?

spring-boot-2.3.2

标签: javaspringspring-boot

解决方案


some_io_calls_q();
some_io_calls_b();

If both your methods do synchronized tasks, then using order is enough.

Your command will be executed following the order annotation. You can print few logs to check about it.

Otherwise, it's not enough with async task. You have to control when/how the task is completed...

The most simple solutions as you describe is calling both method in one commandlinerunner in case you are not sure the internal process of spring.

@DependsOn: only working with process creating bean. It's not relative the execution of commands.


推荐阅读