Application Runner

·

2 min read

Intro:-

Application Runner is an function interface used to execute the code after the Spring Boot application started.Application runners is used to execute piece of code when a Spring Boot Application starts. interfaces are Functional Interfaces, which means they have only one functional method. In order to execute specific piece of code when Spring Boot Application starts, you need to implement these functional interfaces and override the single method of run().Application Runner is used 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. It execute such operations before the Spring Boot’s run() method finishes , because functional interface is suitable for this type of task.

Task:-

you are making basic spring boot app with Application 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.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

b. add annotation

@Component

@SpringBootApplication

c. Implement ApplicationRunner Interface
public class RunnerApplication implements ApplicationRunner

d. apply Bean

@Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("example of application runner");
 //Return the raw unprocessed arguments that were passed to the application.

       Arrays.stream(args.getSourceArgs()).forEach(System.out::println);

    }

your file should be like this-
applicationrunner.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

apprunnerjarcommand.png
Below is the snippet of app

apprunnersnippet.png

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

Conclusion:-

You have implemented the Application Runner interface into a @Component 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 ApplicationRunner Interface.Also by making these app you get acquainted with spring boot basics and ApplicationRunner Basics.