When and why do we need ApplicationRunner and Runner interface?

These runners are used to run the logic on application startup, for example spring boot has ApplicationRunner(Functional Interface) with run method

ApplicationRunner run() will get execute, just after applicationcontext is created and before spring boot application startup.

ApplicationRunner takes ApplicationArgument which has convenient methods like getOptionNames(), getOptionValues() and getSourceArgs().

And CommandLineRunner is also a Functional interface with run method

CommandLineRunner run() will get execute, just after applicationcontext is created and before spring boot application starts up.

It accepts the argument, which are passed at time of server startup.

Both of them provides the same functionality and the only difference between CommandLineRunner and ApplicationRunner is CommandLineRunner.run() accepts String array[] whereas ApplicationRunner.run() accepts ApplicationArguments as argument. you can find more information with example here


In order to use ApplicationRunner or CommandLineRunner interfaces, one needs to create a Spring bean and implement either ApplicationRunner or CommandLineRunner interfaces, both perform similarly. Once complete, your Spring application will detect your bean.

In addition, you can create multiple ApplicationRunner or CommandLineRunner beans, and control the ordering by implementing either

  • org.springframework.core.Ordered interface

  • org.springframework.core.annotation.Order annotation.

use case:

  1. One might wish to log some command line arguments.

  2. You could provide some instructions to the user on termination of this application.

consider:

@Component
public class MyBean implements CommandLineRunner {

    @Override
    public void run(String...args) throws Exception {
        logger.info("App started with arguments: " + Arrays.toString(args));
    }
}

Details on ApplicationRunner


ApplicationRunner and CommandLineRunner are two interfaces Spring Boot provides to run any custom code just before application is fully started.

Spring-batch is a batch processing framework. This uses CommandLineRunner to register and start batch jobs at application startup.

You can also use this interface to load some master data into cache/perform health checks.

The use-case varies from application to application.