Spring Boot Runners – ApplicationRunner and CommandLineRunner

A Guide to Spring Boot RunnersApplication Runner and Command Line Runners – with the help of examples.

What is Spring Boot Runners?

Spring Boot provides two runner interfaces, ApplicationRunner and CommandLineRunner. Being Functional Interfaces, both the runners have a single functional method, run(). When we implement one of these runners, Spring Boot invokes its run() method after it starts the context and before the application starts.

That means we can use Spring Boot CommandLineRunner or ApplicationRunner to execute a piece of code when launching an Application or to create a Spring Boot non-web application.

Difference Between CommandLineRunner and ApplicationRunner

Overall, both CommandLineRunner and ApplicationRunner are similar, and we can use them to do exact same things.

CommandLineRunner (Spring Boot Documentation: Link)

Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple CommandLineRunner beans can be defined within the same application context and can be ordered using the Ordered interface or @Order annotation.

ApplicationRunner (Spring Boot Documentation: Link)

Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple ApplicationRunner beans can be defined within the same application context and can be ordered using the Ordered interface or @Order annotation.

The only difference between the two interfaces is the signature of the run() method. The run() method in the CommandLineRunner receives the application or program argument as an array of String.

void run(String... args)Code language: Java (java)

However, the run() method in ApplicationRunner receives the program arguments wrapped in an ApplicationArguments instance. The ApplicationArguments provides convenient methods to access the program arguments.

void run(ApplicationArguments args)Code language: JavaScript (javascript)

The following sections will teach how to use both ApplicationRunner and CommandLineRunner to execute specific code at a Spring Boot Application startup.

Example of Spring Boot Application Runner

To execute a block of code during a Spring Boot application startup using ApplicationRunner, we need either a Spring Bean or the @SpringBootApplication class implementing the ApplicationRunner interface.

The following is an example of Spring Boot ApplicationRunner implementation that prints all the program arguments to the console. Please note that the class uses one of Spring’s stereotype annotations.

package com.amitph.spring.dogs;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class ApplicationRunnerImpl 
    implements ApplicationRunner {
  
  @Override
  public void run(ApplicationArguments args) throws Exception {
    System.out.println("ApplicationRunner; arguments: ");
    Arrays.stream(args.getSourceArgs())
        .forEach(System.out::println);
  }
}Code language: Java (java)

The run() method reads the program arguments using the ApplicationArguments‘s access method.

Let’s execute the application JAR and pass a few arguments.

~ java -jar dog-service-jpa.jar \
    These are program argumentsCode language: Bash (bash)

The following snippet from the console shows that the run() method correctly printed all the arguments.

o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
com.amitph.spring.dogs.Application       : Started Application in 4.082 seconds (JVM running for 4.511)
ApplicationRunner; arguments: 
These
are
program
argumentsCode language: plaintext (plaintext)

Example of Spring Boot Command Line Runner

Similarly, to use a CommandLineRunner to invoke a block of code at a Spring Boot application startup, we must have a Spring Bean or the @SpringBootApplication implementing the interface.

The following is an example of Spring Boot CommandLineRunner implementation that prints all the program arguments to the console.

package com.amitph.spring.dogs;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class CommandLineRunnerImpl 
    implements CommandLineRunner {
  
  @Override
  public void run(String... args) throws Exception {
    System.out.println("CommandLineRunner; arguments: ");
    Arrays.stream(args)
        .forEach(System.out::println);
  }
}Code language: Java (java)

Let’s run the application, as we did previously and pass a few command line arguments.

o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
com.amitph.spring.dogs.Application       : Started Application in 4.082 seconds (JVM running for 4.511)
CommandLineRunner; arguments: 
These
are
program
argumentsCode language: plaintext (plaintext)

The console snippet shows that the CommandLineRunner correctly printed all the program arguments.

Multiple Spring Boot Runners and their Execution Order

Spring Boot allows us to have multiple implementations of both runners, and both CommandLineRunner and ApplicationRunner can coexist in our application.

When we have multiple Spring Beans implementing either of the runner interfaces, Spring executes their run() method one after the other based on the order of the bean discovery. Spring, however, allows us to use the @Order annotation to set a custom order of the execution for the Spring Boot Runners.

To try it, let’s create a CommandLineRunner implementation with @Order of 1, which indicates the highest priority.

@Order(1)
@Component
public class CommandLineRunnerImpl 
    implements CommandLineRunner {
  ...
}Code language: Java (java)

Next, let’s create an ApplicationRunner implementation with @Order of 2, which is a lower priority.

@Order(2)
@Component
public class ApplicationRunnerImpl 
    implements ApplicationRunner {
  ...
}Code language: Java (java)

Let’s launch the application and pass a few program arguments like we previously did.

com.amitph.spring.dogs.Application       : Started Application in 3.887 seconds (JVM running for 4.309)
CommandLineRunner; arguments: 
These
are
program
arguments
ApplicationRunner; arguments: 
These
are
program
arguments
Code language: plaintext (plaintext)

The console snippet shows that both Spring Boot runners executed one after the other in the specified order.

When to use Spring Boot Runners?

As stated, we can use Spring Boot runners to run a piece of code at the application startup time. Although it may sound simple, runners can perform crucial tasks. The most important thing about the Spring Boot Runners is that they run only after the Spring context is entirely available. That means both CommandLineRunner and ApplicationRunner interfaces can use powerful features like auto-wiring, dependency injection etc.

Following are a couple of Spring Boot Runner use cases.

Setting up Application Level Constants

Applications often must maintain constants or static variables that remain unchanged throughout the application life cycle. Typically, such application-level constants are read from external entities like databases, file systems, or a third-party data provider service. Spring Boot runners are the best place to fetch the constants from external resources and build a local cache.

Initialize Resources

We can also use Spring Boot Runners to initialize various resources to the particular state required by the application. For example, an application may want to execute a few database commands during the startup.

Creating Non-Web Console Application

Also, we can use Spring Boot Runners to build Console applications with Spring Boot. Console applications are non-web applications that we can run to perform a particular task.

Summary

This article discussed Spring Boot Runners with the help of examples. We understood that Spring Boot provides ApplicationRunner and CommandLineRunner interfaces that we can use to execute a code block at application startup. Spring supports multiple implementations of the runners and allows us to provide custom execution orders. We also discussed different use cases we can solve using the ApplicationRunner or CommandLineRunner implementations.

You can refer to our GitHub Repository for the complete source code of the examples used in this tutorial.