Introduction
Spring Boot provides various ways to initialize and execute code when the application starts up. One of the convenient ways to run custom initialization logic is by implementing the CommandLineRunner
interface. In this tutorial, we’ll explore what CommandLineRunner
is, how to use it in a Spring Boot application, and provide examples to demonstrate its usage.
What is CommandLineRunner?
CommandLineRunner
is a functional interface provided by Spring Boot. It is part of the org.springframework.boot
package and contains a single method run()
. This interface is designed to be implemented by Spring Boot components that need to execute custom logic when the application starts up. When the Spring Boot application starts, the run()
method of all beans implementing CommandLineRunner
will be called in the order of their priority.
Implementing CommandLineRunner
To use CommandLineRunner
in your Spring Boot application, you need to follow these steps:
- Create a Spring Bean: Create a Spring Bean and implement the
CommandLineRunner
interface. Override therun()
method to include the initialization logic you want to execute when the application starts. - Annotate the Bean: Annotate the bean class with
@Component
or any other stereotype annotation such as@Service
,@Repository
, etc., to make it a Spring-managed bean. - (Optional) Specify Order: If you have multiple
CommandLineRunner
beans and you want to control the order of their execution, you can annotate them with@Order
and specify the desired order.
Example: Creating a CommandLineRunner Bean
Let’s create a simple example to demonstrate the usage of CommandLineRunner
. Suppose we have a Spring Boot application that needs to print a welcome message when it starts up.
In this example, we’ve created a StartupRunner
class that implements the CommandLineRunner
interface. Inside the run()
method, we print a welcome message to the console.
Ordering CommandLineRunner Beans
If you have multiple CommandLineRunner
beans and you want to specify the order in which they should be executed, you can use the @Order
annotation.
In this example, we’ve created two CommandLineRunner
beans (FirstRunner
and SecondRunner
) and specified their order using the @Order
annotation.
Conclusion
In this tutorial, we’ve explored the CommandLineRunner
interface in Spring Boot and learned how to use it to execute custom initialization logic when the application starts up. We’ve created an example to demonstrate how to implement and annotate a CommandLineRunner
bean, as well as how to specify the order of execution for multiple CommandLineRunner
beans. CommandLineRunner
provides a convenient way to perform startup tasks in Spring Boot applications, making it easier to manage application initialization.