How to execute a Java class at Spring Boot startup

This tutorial will teach you how to execute a Java Class when starting a Spring Boot application by using the CommandLineRunner interface. This interface will run specific code after the Spring application context is fully started but before the application starts receiving requests..

In order to execute method or classes when a Spring Boot application is started you can implement the CommandLineRunner interface, which basically provides just one method: public void run(String… args) that will get called by Spring Boot only once after the application has started.

Example:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.CommandLineRunner;

public class StartupRunner implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());

    @Override
    public void run(String... args) throws Exception {
        logger.info("Start up Runner executed");
    }
}

Then, let’s proceed by defining the StartupRunner as @Bean in the main Spring Boot Application class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class DemoApplication {
  @Bean
  public StartupRunner schedulerRunner() {
    return new StartupRunner();
  }

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

Here is your project view which includes both Classes:

spring boot how to run a class at start up

The CommandLineRunner is an useful approach is helpful for initializing configurations, loading data, or performing any custom operations required at the beginning of the application lifecycle..

Using Lambda Expression for CommandLineRunner

You can also execute the CommandLineRunner implementation directly in the main SpringBoot application Class. In order to do that, you can annotate a method with the @Bean annotation . The method will return the CommandLineRunner implementation. This example uses the Java 8 syntax (lambda) to do that:

package com.example;

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MainApplication {
  private static final Logger log = LoggerFactory.getLogger(MainApplication.class);

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

  @Bean
  String info() {
    return "Hello World!";
  }

  @Autowired String info;

  @Bean
  CommandLineRunner myMethod() {
    return args -> {
      log.info("CommandLineRunner Implementation");
      log.info("Calling Info bean: " + info);
      for (String arg : args) log.info(arg);
    };
  }
}

Choosing the start up Order

We can also use an @Order annotation or implement an Ordered interface so as to define the exact order in which we want Spring Boot to execute them. For example, Spring Batch relies on the runners in order to trigger the execution of the jobs.

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class FirstRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("FirstRunner executed");
    }
}

@Component
@Order(2)
public class SecondRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("SecondRunner executed");
    }
}

ApplicationReadyEvent vs. CommandLineRunner

Command Line Runner is not the only approach to execute code at start up in a Spring Boot application. You can also rely on ApplicationReadyEvent as you can learn in this article: Using ApplicationReadyEvent to run code at Spring Boot startup

In this section we will highlight the differences between the two approaches:

ApplicationReadyEvent

  • Event-based Execution: ApplicationReadyEvent is triggered when the Spring application context is fully initialized and the application is ready to handle requests.
  • Asynchronous Execution: Code executed within the ApplicationReadyEvent is asynchronous, meaning it occurs after the entire application context has been set up and is ready to serve requests.
  • Use Cases: Ideal for tasks that require the entire Spring context to be initialized, such as database initialization, setting up caches, scheduling tasks, or performing operations that depend on other Spring beans.

CommandLineRunner

  • Interface-based Execution: CommandLineRunner is an interface in Spring Boot that allows you to run specific code after the Spring application context is fully started but before the application starts receiving requests.
  • Synchronous Execution: The run() method of CommandLineRunner is synchronous and is executed sequentially before the application is fully operational.
  • Use Cases: Suited for tasks that need to run before the application starts handling requests, like performing initialization operations, checking configurations, or executing specific tasks required for the application’s start.

Key Differences:

  1. Timing of Execution:
    • ApplicationReadyEvent executes after the application context is fully initialized and is ready to serve requests.
    • CommandLineRunner executes before the application starts handling requests but after the context is set up.
  2. Synchronous vs. Asynchronous:
    • CommandLineRunner runs synchronously, potentially blocking the application startup process until the code within the run() method completes.
    • ApplicationReadyEvent runs asynchronously, allowing the application to start serving requests while the event-listening code executes in the background.

Conclusion:

Utilizing the CommandLineRunner interface in Spring Boot allows you to execute specific logic or tasks during the application’s startup. This approach is helpful for initializing configurations, loading data, or performing any custom operations required at the beginning of the application lifecycle.

Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon