How to Use CommandLineRunner in Spring Boot Application

CommandLineRunner is a simple spring boot interface with a run method. The run method of all beans implementing the CommandLineRunner interface will be called automatically by the spring boot system after the initial boot. To see CommandLineRunner in action, just add the following class to your existing Spring Boot Application. When you run your application, you will see the run method output in the console.

package com.example;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner{

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Hello From MyCommandLineRunner");
        System.out.println("Printing all comandline arguments");
        System.out.println(Arrays.toString(args));   
    }
}

The spring boot console shows that the run method of MyCommandLineRunner is executed automatically.

commandlinerunner in spring boot

Spring component scanner picks up all the CommandLineRunner implementations and automatically executes run method inside them. The command  line parameters to spring boot is passed as parameters to the run method. If you want ordering of multiple CommandLineRunner instances, you need to implement the @Ordered interface. The following CommandLineRunner implementations demonstrate the use of @Ordered interface.

package com.example;

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

@Component
public class FirstCommandLineRunner implements CommandLineRunner, Ordered {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Running First CommandLineRunner");

    }

    @Override
    public int getOrder() {
        return 1;
    }
}

 

package com.example;

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

@Component
public class SecondCommandLineRunner implements CommandLineRunner, Ordered {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Running Second CommandLineRunner");
    }

    @Override
    public int getOrder() {
        return 2;
    }
}

Run the spring boot and verify that run methods are executed in the specified order.

order-commandlinerunner-spring-boot

References