Spring Boot Runners: CommandLine vs Application

Spring-boot-runner-commandlinerunner-applicationrunners

In this comprehensive guide on Spring Boot Runners, we will explore the powerful capabilities of ApplicationRunners and CommandLineRunners. These essential components play a vital role in executing tasks during the startup phase of your Spring Boot application. We will delve into their usage, differences, and how to harness their potential for various initialization tasks.

What Are CommandLineRunners and ApplicationRunners?

Startup activities are essential for preparing an application before it goes into full execution mode. For instance:

1. Data Loading and Cache Initialization

Imagine a scenario where you need to load data from a source system and initialize a cache, which has been configured as a bean definition in the IoC container. This data loading into the cache is a one-time startup activity.

2. Database Schema Creation

In another scenario, you might need to create a database schema by running an SQL script before your application kicks off. Typically, this activity is not performed during JUnit test executions.

In a Spring Core application, handling startup activities is straightforward. You can execute these activities after creating the IoC container but before using it. Here’s an example in Java:

Java
ApplicationContext context = new AnnotationConfigApplicationContext(JavaConfig.class);
// Perform startup activities
Tank tank = context.getBean(Tank.class); // Use IoC container
tank.level();

However, in a Spring MVC application, the IoC container is created by the DispatcherServlet and ContextLoaderListener, and you don’t have a chance to execute post-construction activities. This limitation led to the introduction of a unified approach in Spring Boot.

Spring Boot Runners: A Unified Approach

Spring Boot provides a standardized way of starting up Spring applications, be it core or web applications, by using SpringApplication.run(). This method ensures consistent initialization of your application. All startup activities are streamlined by leveraging the SpringApplication class.

To execute startup activities in Spring Boot, SpringApplication offers a callback mechanism through CommandLineRunners and ApplicationRunners. You can write code inside classes that implement these interfaces, overriding their respective methods

Key Differences Between CommandLineRunners and ApplicationRunners

Before we delve into practical examples, let’s understand the key differences between CommandLineRunners and ApplicationRunners:

FeatureCommandLineRunnerApplicationRunner
Access to Command-Line ArgumentsReceives command-line arguments as an array of strings (String[] args) in the run method.Receives command-line arguments as an ApplicationArguments object in the run method, allowing access to both operational and non-operational arguments.
UsageIdeal for simpler cases where access to command-line arguments is sufficient.Suitable for scenarios where more advanced command-line argument handling is required, such as working with non-option arguments and option arguments.
Comparison Between CommandLineRunners and ApplicationRunners

1. CommandLineRunner Example

First, let’s create a CommandLineRunner class. You can place it in a package of your choice, but for this example, we’ll use the package com.runners.

Java
package com.runners;

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

/**
 * @author Pavan Kumar
 */
@Component
public class MyCommandLineRunner implements CommandLineRunner {

	@Override
	public void run(String... args) throws Exception {
		System.out.println("Command-line arguments for CommandLineRunner:");
		for (String arg : args) {
			System.out.println(arg);
		}
	}
}

This class implements the CommandLineRunner interface and overrides the run method. Inside the run method, we print the command-line arguments passed to our application.

2. ApplicationRunner Example

Now, let’s create an ApplicationRunner class. The process is similar to creating the CommandLineRunner class.

Java
package com.runners;

import java.util.List;

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

/**
 * @author Pavan Kumar
 *
 */

@Component
public class MyApplicationRunner implements ApplicationRunner {

	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("ApplicationRunner Arguments....");
		for (String arg : args.getSourceArgs()) {
			System.out.println(arg);
		}

		System.out.println("Non-option arguments:");
		List<String> nonOptionalList = args.getNonOptionArgs();
		for (String nonOptArgs : nonOptionalList) {
			System.out.println(nonOptArgs);
		}

		System.out.println("Option arguments:");
		for (String optArgName : args.getOptionNames()) {
			System.out.println(optArgName + " : " + args.getOptionValues(optArgName));
		}

	}
}

This class implements the ApplicationRunner interface, where we override the run method. Inside this method, we print command-line arguments obtained from the ApplicationArguments object, enabling effective access to both operational and non-operational arguments.

The MyApplicationRunnerExample class extends the capabilities of ApplicationRunner, displaying both non-option and option arguments.

3. Using CommandLineRunners and ApplicationRunners

Now that you’ve created and integrated CommandLineRunner and ApplicationRunner classes, including MyApplicationRunnerExample, you can use them to execute tasks during your Spring Boot application’s startup.

  1. Run Your Spring Boot Application: Open your command prompt or terminal, navigate to your project directory, and enter the following command to start your Spring Boot application:
Bash
java -jar target/boot-runners-0.0.1-SNAPSHOT.jar arg1, arg2, arg3 --option1=value1 --option2=value2

Replace boot-runners-0.0.1-SNAPSHOT.jar with the actual name of your application’s JAR file.

  1. Observe Output: As your application starts, you’ll notice that all three runner classes (MyCommandLineRunner, MyApplicationRunner) are executed automatically. They will display various command-line arguments passed to your application.

Output:

By following these steps and examples, you’ve successfully implemented CommandLineRunners and ApplicationRunners in your Spring Boot application. You can customize these classes to perform various tasks like initializing databases, loading configurations, or any other startup activities your application may require.

With the flexibility provided by CommandLineRunners and ApplicationRunners, you can tailor your application’s initialization process to meet your specific needs, making Spring Boot a powerful choice for building robust applications.

You can explore more information about Spring Boot Runners on the GitHub repository https://github.com/askPavan/boot-runners where you might find practical examples and code samples related to CommandLineRunners and ApplicationRunners.

Additionally, you can refer to external resources such as:

  1. Spring Boot Documentation: The official Spring Boot documentation provides in-depth information about CommandLineRunners and ApplicationRunners.

Related Articles: