🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this tutorial, we will learn how to use Spring Boot CommandLineRunner interface in spring boot applications.
Note that we have added @Component annotation to the ApplicationRunner class so that it will auto scanned during classpath scanning.
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:
- Using CommandLineRunner as @Component (spring component)
- Implement CommandLineRunner in Spring Main class (Annotated with @SpringBootApplication annotation)
- 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");
}
}
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
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment