Spring Boot multiple CommandLineRunner execution order and state

Viewed 210

I have some startup operations to be executed one after another. Both of these runners performs some heavy database operations.

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

}

I need to make sure that @Order(2) runner starts only after @Order(1) has finished it's processing.

Is there any way to achieve this, like registering the runners onto some strategies so that they can be monitored for their completion.

I found a way, like, I can go for waiting till the value of a singleton scoped bean variable turns true, which is set only when first runner finishes it's task. But I'm afraid if this is recommended or not.

Or, can I rely on @DependsOn for the task completion? Is is guaranteed that, by using @DependsOn("MyFailureHandlerA") over MyFailureHandlerB will guaranteee that 1st runner has completed it's entire operations?

Another way I was trying is, invoking the services call one after another from one single runner, like this:

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

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

}

Would this makes some sense and will ensure that ops are executed in order one after another?

spring-boot-2.3.2

1 Answers
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.

Related