Spring Boot CommandLineRunner Example: 3 Ways to Use

Spring boot’s CommandLineRunner interface is used to run a code block only once in the application’s lifetime – after the application is initialized and ready to process commands passed through the command line. Generally, this is used for performing tasks like initializing the application, loading data, or running background processes.

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println("Spring Boot application has started!");
    //... custom code ...
  }
}

1. CommandLineRunner Interface

The CommandLineRunner interface is part of the org.springframework.boot package and has a single method:

void run(String... args) throws Exception;

When the Spring Boot application starts up, it will detect any beans that implement the CommandLineRunner interface and automatically invoke their run method.

The arguments passed from the command line can be accessed from the method argument ‘args‘.

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

  //...

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

    //...
    
    if (args.length > 0) {
      System.out.println("Command-line arguments:");
      for (String arg : args) {
          System.out.println(arg);
      }
    } else {
      System.out.println("No command-line arguments provided.");
    }
  }
}

2. Different Ways to Use the CommandLineRunner?

We can use CommandLineRunner interface in three ways:

2.1. Implement CommandLineRunner Interface

This is the simplest and most straightforward approach. Generally, we implement the CommandLineRunner interface in @SpringBootApplication annotated class, though it is not mandatory.

@SpringBootApplication
public class Application implements CommandLineRunner {

  public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
  }
 
  @Override
  public void run(String... args) throws Exception {

    // Code to run...
  }
}

2.2. CommandLineRunner as @Component

This one is fairly easy and works quite similar to the previous approach. In this approach, rather using the @SpringBootApplication, we register the class as bean using the @Component annotation.

@Component
public class ApplicationStartupRunner implements CommandLineRunner {
 
  @Override
  public void run(String... args) throws Exception {

    // Code to run...
  }
}

2.3. Using CommandLineRunner as Bean

If the class, implementing the CommandLineRunner interface, is not annotated with any stereotype annotations then we can declare it as a bean in any @Configuration class.

ApplicationStartupRunner.java implements the CommandLineRunner interface and does not have @Component annotation.

public class ApplicationStartupRunner implements CommandLineRunner {

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

    // Code to run...
  }
}

We register ApplicationStartupRunner class as a bean using the @Bean annotation.

@SpringBootApplication
public class Application {
 
  public static void main(String[] args) throws Exception {
    SpringApplication.run(Application.class, args);
  }
 
  @Bean
  public ApplicationStartupRunner schedulerRunner() {
    return new ApplicationStartupRunner();
  }
}

It is important to note that if any exceptions are thrown inside the run(String… args) method, this will cause the context to close and an application to shut down. So put risky code in ‘try-catch‘ block – ALWAYS.

3. Using @Order if multiple CommandLineRunner interface implementations

You may have multiple implementations of the CommandLineRunner interface. By default, Spring Boot scans all its run() methods and executes them. But if you want to force some ordering in them, use @Order annotation.

@Order(value=3)
@Component
class ApplicationStartupRunnerOne implements CommandLineRunner {
  protected final Log logger = LogFactory.getLog(getClass());
 
  @Override
  public void run(String... args) throws Exception {
    logger.info("ApplicationStartupRunnerOne run method Started !!");
  }
}
 
@Order(value=2)
@Component
class ApplicationStartupRunnerTwo implements CommandLineRunner {
  protected final Log logger = LogFactory.getLog(getClass());
 
  @Override
  public void run(String... args) throws Exception {
    logger.info("ApplicationStartupRunnerTwo run method Started !!");
  }
}

Verify the logs.

2017-03-08 13:55:04 - ApplicationStartupRunnerTwo run method Started !!
2017-03-08 13:55:04 - ApplicationStartupRunnerOne run method Started !!

4. When to use?

  • Command line runners are a useful functionality to execute the various types of code that only have to be run once, right after application startup.
  • FYI, Spring Batch relies on these runners in order to trigger the execution of the jobs.
  • We can use the dependency injection to our advantage in order to wire in whatever dependencies that we need and in whatever way we want – in run() method implementation.

5. Difference Between CommandLineRunner and ApplicationRunner

Similar to CommandLineRunner, Spring Boot provides another interface called ApplicationRunner which serves a similar purpose. The only main difference between them is in the way command-line arguments are handled.

The CommandLineRunner accepts command-line arguments as an array of strings (String[] args), while ApplicationRunner accepts them as an ApplicationArguments object. The ApplicationArguments instance allows to access the application arguments as non-option arguments, option arguments, and source arguments.

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class MyApplication {

  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}

@Component
class MyApplicationRunner implements ApplicationRunner {

  @Override
  public void run(ApplicationArguments args) throws Exception {
    System.out.println("Spring Boot application has started!");

    if (!args.getNonOptionArgs().isEmpty()) {
        System.out.println("Non-option arguments:");
        args.getNonOptionArgs().forEach(System.out::println);
    } else {
        System.out.println("No non-option arguments provided.");
    }
  }
}

6. Conclusion

This Spring Boot tutorial discussed the CommandLineRunner interface and its purpose with examples. We also saw a similar interface ApplicationRunner and how it is different from the CommandLineRunner.

Happy Learning !!

Comments

Subscribe
Notify of
guest
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.