🌱 Spring Boot Q25 / 69

What is ApplicationRunner in Spring Boot?

AI-Powered Answer ✓ Answered

ApplicationRunner is an interface in Spring Boot that allows you to run specific code once the Spring Boot application has started up and the ApplicationContext has been fully loaded. It's commonly used for executing tasks that need to run immediately after the application is ready, such as initializing data, performing validation, or executing background services.

What is ApplicationRunner?

The ApplicationRunner interface provides a single method, run(ApplicationArguments args), which is automatically invoked by Spring Boot right before the application starts accepting requests (for web applications) or finishes its main method (for non-web applications). This makes it an ideal hook for executing any code that depends on the fully initialized Spring container.

Key Characteristics

  • Single Method: It has one abstract method: void run(ApplicationArguments args) throws Exception;
  • Post-Context Initialization: The run method is executed after all Spring beans have been created and initialized, and the ApplicationContext is fully ready.
  • Access to ApplicationArguments: It provides access to ApplicationArguments, which is a parsed version of command-line arguments, making it easier to work with options and non-option arguments.
  • Ordered Execution: Multiple ApplicationRunner beans can be defined. Their execution order can be controlled using the @Order annotation or by implementing the Ordered interface.

How to Use It

To use ApplicationRunner, you simply create a class, implement the ApplicationRunner interface, override the run method with your desired logic, and annotate the class with @Component (or register it as a bean in your configuration).

Example

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

@Component
public class MyStartupRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("\\n--- ApplicationRunner executed ---");
        System.out.println("Non-option arguments: " + args.getNonOptionArgs());
        System.out.println("Option arguments: " + args.getOptionNames());

        if (args.containsOption("my-arg")) {
            System.out.println("Value of 'my-arg': " + args.getOptionValues("my-arg"));
        }

        System.out.println("Application is now fully operational!");
        System.out.println("-----------------------------------\n");
    }
}

ApplicationArguments

The ApplicationArguments object provides a more structured way to access command-line arguments compared to a raw String[]. It distinguishes between option arguments (prefixed with --, e.g., --debug, --server.port=8080) and non-option arguments (e.g., profile test). You can easily retrieve them using methods like getOptionNames(), getOptionValues(String name), and getNonOptionArgs().

Comparison with CommandLineRunner

Spring Boot also provides CommandLineRunner, which is very similar to ApplicationRunner. The main difference lies in the argument type passed to their run methods: * CommandLineRunner: void run(String... args) throws Exception; (receives raw command-line arguments). * ApplicationRunner: void run(ApplicationArguments args) throws Exception; (receives parsed ApplicationArguments). For most use cases, ApplicationRunner is preferred due to its convenient parsing of command-line arguments.

When to Use It

  • Initial Data Setup: Populating a database with default or test data when the application starts.
  • Resource Validation: Checking the availability or correctness of external resources (e.g., file paths, external services) required by the application.
  • Scheduled Task Initialization: Starting background threads or scheduled jobs that are part of the application logic.
  • Logging Startup Information: Printing out key configuration details or status messages after the application is fully loaded.
  • Executing One-Time Tasks: Performing any task that needs to run exactly once after the Spring context is ready, but before the main application logic proceeds.