Total Pageviews

2020/01/05

[Java] JCommander Quck Start

Requirement
Assume I will run my jar file with one parameter as following:
F:\git\batch-job\target>java -jar batch-0.0.1-SNAPSHOT.jar -name Job2

Maven Dependency
Add JCommander in your pom.xml
    <properties>
        <java.version>1.8</java.version>
        <com.beust.jcommander.version>1.78</com.beust.jcommander.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>com.beust</groupId>
            <artifactId>jcommander</artifactId>
            <version>${com.beust.jcommander.version}</version>
        </dependency>
    </dependencies>


Create Argument Class
package com.test.batch.parameter;

import com.beust.jcommander.Parameter;
import lombok.Data;

@Data
public class BatchJobArgument {

    @Parameter(names = "-name", description = "batch job name")
    private String name;

    @Parameter(names = {"-help", "-h"}, help = true, description = "display help message")
    private boolean help;

}


Update Spring boot application class
package com.test.batch;

import com.beust.jcommander.JCommander;
import com.test.batch.parameter.BatchJobArgument;
import com.test.batch.service.JobExecutor;
import com.google.common.base.Strings;
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) {
        BatchJobArgument arguments = new BatchJobArgument();

        JCommander jCommander = JCommander.newBuilder().build();
        jCommander.addObject(arguments);
        jCommander.parse(args);

        if(arguments.isHelp()){
            jCommander.usage();
            return;
        }

        log.debug("arguments = {}", arguments);

        if(Strings.isNullOrEmpty(arguments.getName())) {
            log.debug("Please assign job name (ex. -name Job1)");
        }else{
            jobExecutor.execute(arguments.getName());
        }
    }

}


Check result
[           main] com.test.batch.BatchApplication  : arguments = BatchJobArgument(name=Job2)






No comments: