Total Pageviews

2020/01/04

[Spring Boot] How to implement Spring Boot Console Application

Maven Dependency
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
Then using Spring's @SpringBootApplication annotation on our main class to enable auto-configuration.

This class also implements Spring's CommandLineRunner interface. CommandLineRunner is a simple Spring Boot interface with a run method. Spring Boot will automatically call the run method of all beans implementing this interface after the application context has been loaded.
package com.test.batch;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@Slf4j
@SpringBootApplication
public class BatchApplication implements CommandLineRunner {

    private final JobExecutor jobExecutor;

    public BatchApplication(JobExecutor jobExecutor) {
        this.jobExecutor = jobExecutor;
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(BatchApplication.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
    }

    @Override
    public void run(String... args) {
        // receive arguments in run method
        if (args != null && args.length > 0) {
            String argument = args[0];
            log.debug("argument = {}", argument);
            jobExecutor.execute(argument);
        } else {
            log.debug("no argument found");
        }
    }

}

No comments: