How to use CommandLineRunner in Spring Boot Application?
CommandLineRunner Interface is a functional interface provided by Spring Boot. The main purpose of this interface to execute a code block once before the application has finished startup. In this article, I will be addressing the need for the CommandLineRunner Interface as well as how and when to use it.
GitHub Source Code - Clone Repo
Spring Boot provides two Interface (Remember its an interface) CommandLineRunner and ApplicationRunner. Since CommandLineRunner is an interface so we must implement the CommandLineRunner interface into our class.
Name : - CommandLineRunner
Type : - Interface
Overriding method : - run()
Note:- With the new release of Spring Boot v2.6 there are nothing changes in terms of application runner
Table of Content
- Why do we need CommandLineRunner?
- Lets Jump to Code
- When to use CommandLineRunner?
- Ordering
- Conclusion
1. Why do we need CommandLineRunner?
To answer the need of CommandLineRunner -Let's say you have need to run Scheduled batch Job, set some system environment properties, or need to perform some DB operation just before the Spring Boot run() method is finished, so in this kind of scenario CommandLineRunner Interface comes handy. It allows you to do such an operation before the Spring Boot's run() method finishes its execution.
2. Lets Jump to Code
As per API documentation, CommandLineRunner is an Interface, so we can not create an instance of it but we can implement it.
1package com.jhooq.springbootcommandlinerunner;
2
3import org.slf4j.Logger;
4import org.slf4j.LoggerFactory;
5import org.springframework.boot.CommandLineRunner;
6import org.springframework.boot.SpringApplication;
7import org.springframework.boot.autoconfigure.SpringBootApplication;
8
9/**
10 * Author : Rahul Wagh
11 **/
12@SpringBootApplication
13public class SpringBootCommandLineRunner implements CommandLineRunner {
14
15 private static Logger LOG = LoggerFactory
16 .getLogger(SpringBootCommandLineRunner.class);
17
18 public static void main(String[] args) {
19 LOG.info("STARTING : Spring boot application starting");
20 SpringApplication.run(SpringBootCommandLineRunner.class, args);
21 LOG.info("STOPPED : Spring boot application stopped");
22 }
23
24 @Override
25 public void run(String... args) throws Exception {
26 LOG.info("EXECUTING : command line runner");
27
28 for(int i=0;i<=10;i++){
29 LOG.info("Count ="+i);
30 }
31 }
32
33}
Console Output
1[main] c.j.s.SpringBootCommandLineRunner: Starting SpringBootCommandLineRunner on Rahul-PC with PID 1776
2[main] c.j.s.SpringBootCommandLineRunner: No active profile set, falling back to default profiles: default
3[main] c.j.s.SpringBootCommandLineRunner: Started SpringBootCommandLineRunner in 1.815 seconds (JVM running for 3.31)
4[main] c.j.s.SpringBootCommandLineRunner: EXECUTING : command line runner
5[main] c.j.s.SpringBootCommandLineRunner: Count =0
6[main] c.j.s.SpringBootCommandLineRunner: Count =1
7[main] c.j.s.SpringBootCommandLineRunner: Count =2
8[main] c.j.s.SpringBootCommandLineRunner: Count =3
9[main] c.j.s.SpringBootCommandLineRunner: Count =4
10[main] c.j.s.SpringBootCommandLineRunner: Count =5
11[main] c.j.s.SpringBootCommandLineRunner: Count =6
12[main] c.j.s.SpringBootCommandLineRunner: Count =7
13[main] c.j.s.SpringBootCommandLineRunner: Count =8
14[main] c.j.s.SpringBootCommandLineRunner: Count =9
15[main] c.j.s.SpringBootCommandLineRunner: Count =10
16[main] c.j.s.SpringBootCommandLineRunner: STOPPED : Spring boot application stopped
3. When to use CommandLineRunner?
CommandLineRunner can be used in the following scenarios : -
- One common use case for
CommandLineRunner
is to parse command line arguments and configure the application based on those arguments. For example, you might useCommandLineRunner
to set a default value for a configuration property if it is not provided as a command line argument, or to enable or disable certain features of the application based on command line arguments. - Another use case for
CommandLineRunner
is to perform any one-time tasks that need to be run after the application has started, but before it is fully ready to handle requests. For example, you might useCommandLineRunner
to initialize a database or load data into the application.
Here are few more concrete use cases of CommandLineRunner -
- Need to add some additional logger information
- Schedule a batch job
- Database operation i.e. cleanup script, status update
Gotcha for option and nonoption argument
CommandLineRunner doesn't care about the option and non-option argument, it will take all the args as an array of strings. Take a closer look at the output.
1[main] c.j.s.SpringBootCommandLineRunner: EXECUTING : command line runner
2[main] c.j.s.SpringBootCommandLineRunner: ARGS : - [--arg1=Jhooq, --arg2=CommanLineRunner]
3[main] c.j.s.SpringBootCommandLineRunner: STOPPED : Spring boot application stopped
As you can see from the above console output, CommandLineRunner can not distinguish between the following parameters
- -arg1=Jhooq
- -arg2=CommanLineRunner All the above three arguments are treated as Array of String.
But not to worry Spring Boot provides one more interface ApplicationRunner which can be used to accomplish or identify the optional and non-optional arguments. For more details about ApplicationRunner please refer to - Application Runner
4. Ordering
The one more feature provided by the Spring Boot CommandLine Runner is @Order annotation. In a Spring Boot Application Context you can have multiple CommandLine Runner but in order to execute those you must provide order using @Order
Here is example of @Order annotation used along with CommandLine Runner -
1@SpringBootApplication
2@Order(1)
3public class SpringBootCommandLineRunner implements CommandLineRunner {
4
5 private static Logger LOG = LoggerFactory
6 .getLogger(SpringBootCommandLineRunner.class);
7
8 public static void main(String[] args) {
9 SpringApplication.run(SpringBootCommandLineRunner.class, args);
10 }
11
12 @Override
13 public void run(String... args) throws Exception {
14 LOG.info("EXECUTING : command line runner in order ");
15
16 for(int i=0;i<=10;i++){
17 LOG.info("Count ="+i);
18 }
19 }
20
21}
22
5. Conclusion
I hope this little tutorial might have helped you to get a better understanding of "How to use CommandLineRunner Interface".
If you have any questions or queries please put your comments below and I will be happy to answer you.