Spring Boot CommandLineRunner Example Tutorial

In this tutorial, we will learn how to use Spring Boot CommandLineRunner interface in spring boot applications.
Learn spring boot at https://www.javaguides.net/p/spring-boot-tutorial.html

Video Tutorial

This tutorial explained in below YouTube video:

1. Spring Boot CommandLineRunner interface overview

CommandLineRunner is an interface used to indicate that a bean should run when it is contained within a SpringApplication. A Spring Boot application can have multiple beans implementing CommandLineRunner. These can be ordered with @Order.
Read more about the CommandLineRunner interface at JavaDoc.

2. How to use CommandLineRunner

You can use the CommandLineRunner interface in three ways:
  1. Using CommandLineRunner as @Component (spring component)
  2. Implement CommandLineRunner in Spring Main class (Annotated with @SpringBootApplication annotation)
  3. Using CommandLineRunner as Bean (using @Bean annotation)

1) Using CommandLineRunner as @Component

Create ApplicationRunner class which implements CommandLineRunner interface like:
@Component
public class ApplicationRunner implements CommandLineRunner{
    @Override
    public void run(String... args) throws Exception {
        System.out.println(" ApplicationRunner called");
    }
}
Note that we have added @Component annotation to the ApplicationRunner class so that it will auto scanned during classpath scanning.

2) Implement CommandLineRunner in @SpringBootApplication

@SpringBootApplication
public class SpringBootWebApplication implements CommandLineRunner {

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

    @Override
    public void run(String...args) throws Exception {
        System.out.println("Application Started !!");
    }
}
The SpringBootWebApplication class implements CommandLineRunner interface and provides implementation for run() method.

3) Using CommandLineRunner as Bean

You can define a bean in SpringBootApplication which returns the class that implements the CommandLineRunner interface.
package net.javaguides.springboot;

import org.springframework.boot.CommandLineRunner;


public class ApplicationRunner implements CommandLineRunner {
    @Override
    public void run(String...args) throws Exception {
        System.out.println(" ApplicationRunner called");
    }
}
Register ApplicationStartupRunner bean:
package net.javaguides.springboot;

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

@SpringBootApplication
public class SpringBootWebApplication {

    @Bean
    public ApplicationRunner applicationStartupRunner() {
        return new ApplicationRunner();
    }

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

3. Using @Order if multiple CommandLineRunner interface implementations

You may have multiple implementations of the CommandLineRunner interface. By default, spring boot to scan all its run() methods and execute it. But if you want to force some order in them, use @Order annotation.
@Order(value=3)
@Component
class BeanOne implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());
 
    @Override
    public void run(String... args) throws Exception {
        System.out.println("BeanOne run method Started !!");
    }
}
@Order(value=2)
@Component
class BeanTwo implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());
 
    @Override
    public void run(String... args) throws Exception {
        System.out.println("BeanTwo run method Started !!");
    }
}
@Order(value=1)
@Component
class BeanThree implements CommandLineRunner {
    protected final Log logger = LogFactory.getLog(getClass());
 
    @Override
    public void run(String... args) throws Exception {
        System.out.println("BeanThree run method Started !!");
    }
}

4. Insert Database Records while Application started

Command-line runners are a useful functionality to execute the various types of code that only have to be run once, right after application startup.
Sometimes we need to insert records into a database while application startup, for example:

MyRunner Class

package net.guides.springboot.jparepository;

import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import net.guides.springboot.jparepository.model.Employee;
import net.guides.springboot.jparepository.repository.EmployeeRepository;

@Component
public class MyRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(MyRunner.class);

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public void run(String...args) throws Exception {

        employeeRepository.save(new Employee("Ramesh", "Fadatare", "ramesh@gmail.com"));
        employeeRepository.save(new Employee("Tom", "Cruise", "tom@gmail.com"));
        employeeRepository.save(new Employee("John", "Cena", "john@gmail.com"));
        employeeRepository.save(new Employee("tony", "stark", "stark@gmail.com"));

        logger.info("# of employees: {}", employeeRepository.count());

        logger.info("All employees unsorted:");

        Iterable < Employee > employees = employeeRepository.findAll();
        Iterator < Employee > iterator = employees.iterator();
        while (iterator.hasNext()) {
            logger.info("{}", iterator.next().toString());
        }

        logger.info("------------------------");

        logger.info("Deleting employee with id 1");
        employeeRepository.deleteById(1 L);

        logger.info("# of employees: {}", employeeRepository.count());

        employeeRepository.existsById(2 L);
        employeeRepository.findById(2 L);
    }
}
Read the complete example at https://www.javaguides.net/2019/06/spring-boot-crudrepository-example-tutorial.html.

5. Conclusion

We have looked into different ways to use the CommandLineRunner interface in spring boot application and how to use the CommandLineRunner interface to insert records in a database.
Follow me at https://www.javaguides.net/p/about-me.html

Comments