CommandLineRunner

·

2 min read

Intro:-

Spring Boot provides CommandLineRunner interface , to run some code when an application is started. These interfaces get called just before run() and This interface provides access to application arguments as string array.(run(String... args)) You can register as many command line runners according to your requirements. You just need to register them as Beans in the application context. Then, Spring boot will auto magically pick it up. You can order them as well either by extending interface org.springframework.core.Ordered or via the @Order annotation.

Task:-

you are making basic spring boot app with CommandLine Runner.

Software Requirements:-

Ubuntu-20.04 +jit [linux-x86_64]
Open Jdk 8
Spring Boot 2.2

Level:-

Beginner

Prerequisite:-

Knowledge of core java and text editor

Step 1:-

Using Spring Initializr(start.spring.io) download starter app by filling required parameters. Unzip the folder at your computer.

Step 2:-

Create executable JAR file please refer here

Step 3:-

a. import following in your main application file, in my case, it is
RunnerApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.CommandLineRunner;

b. add annotation

@SpringBootApplication   
 @Override

c. Implement CommandLineRunner Interface
public class RunnerApplication implements CommandLineRunner

d. apply Bean

@Override
   public void run(String... arg0) throws Exception {
      System.out.println("DevNation from Command Line Runner");
   }

your file should be like this-

clr1.png

Step 4:-

package the Spring Boot app into a JAR and execute it by passing a few parameters.
$ java -jar target/runner-0.0.1-SNAPSHOT.jar this is application runner

clr2.png Below is the snippet of app

commandlinerunner.png

The application is fully started and it also prints each of the argument on separate lines.

Conclusion:-

You have implemented the CommandLine Runner interface via spring bean, which overrides the run() method.And the bean gets executed when the application is started.
After performing above steps you made a spring boot nano app,and uses CommandLineRunner Interface.Also by making these app you get acquainted with spring boot basics and CommandLineRunner Basics.