How CommandLineRunner works in Spring Boot ?

In Spring Boot, CommandLineRunner is an interface used to execute code after the application context has been initialized.

Use Cases:

  • Run startup logic (e.g., initialize data in the database).
  • Execute batch jobs or scheduled tasks on startup.
  • Perform configuration checks before the application starts.
  • Useful for testing/debugging.

How to Use CommandLineRunner?

CommandLineRunner has one method to implement:

void run(String... args);

1. Basic Example

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

@Component
public class StartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("Application has started! Running startup logic...");
    }
}

Since it’s marked with @Component, Spring Boot automatically runs it at startup.


2. Running SQL Commands on Startup

Use case: Insert test data in an H2/MySQL/PostgreSQL database when the app starts.

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

@Component
public class DatabaseSeeder implements CommandLineRunner {

    @Autowired
    private EntityManager entityManager;

    @Override
    @Transactional
    public void run(String... args) {
        System.out.println("Seeding initial database records...");
        
        entityManager.createNativeQuery("INSERT INTO USERS (name, email) VALUES ('Alice', 'alice@example.com')").executeUpdate();
        entityManager.createNativeQuery("INSERT INTO USERS (name, email) VALUES ('Bob', 'bob@example.com')").executeUpdate();

        System.out.println("Database seeding completed!");
    }
}

Note : Automatically seeds data when the application starts.


3. Multiple Runners in a Spring Boot Application

You can have multiple CommandLineRunner beans, and Spring Boot will execute them in no particular order.

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

@Component
public class AnotherStartupTask implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("Executing another startup task...");
    }
}

Note : Spring Boot executes all CommandLineRunner beans on startup.


4. Using CommandLineRunner in the Main Application Class

Instead of a separate class, you can define a CommandLineRunner bean in your @SpringBootApplication class.

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

@SpringBootApplication
public class MyApp {

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

    // Define a CommandLineRunner Bean
    public CommandLineRunner startupTask() {
        return args -> {
            System.out.println("Executing startup task inside main application class!");
        };
    }
}

5. Using Order to Control Execution Sequence

If multiple CommandLineRunner beans exist, you can set execution order using @Order.

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

@Component
@Order(1) // Runs first
public class FirstTask implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("First task executing...");
    }
}

@Component
@Order(2) // Runs second
public class SecondTask implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("Second task executing...");
    }
}

Note: Ensures controlled execution order.


6. Summary

FeatureCommandLineRunner
PurposeRun logic after application startup
Methodvoid run(String... args)
Where to use?Inside @Component or as a Bean in @SpringBootApplication
Use CasesInitialize DB, run batch jobs, logging, startup checks
Execution OrderControlled via @Order(n)

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *