How to mimic apache cli arguments with spring-boot ApplicationArguments?

843 views Asked by At

So I've spring-boot application which is focused to be a command line AppplicationRunner. Let just say it has some default properties and then needs a URL which is then consumes.

I want to use the default @Configuration annotations to load default values from the internal properties file but i need to inform the user who is executing the application of the mandatory arguments. ie the URL.

In the tranditional java application i'd pull in the help of apache-commons-cli and define argument options like

public static void main(String[] args) throws Exception {
    try {
        // Command line args parsing
        CommandLineParser commandLineParser = new DefaultParser();
        Options options = new Options();
        options.addOption("h", "help", false, "Usage description");
        options.addOption("url", "url", true, "Mandatory : The URL");

Within the spring-boot API there is the ApplicationArguments class which seems to provide an interface to access command line arguments

@SpringBootApplication
public class Application implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String... args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("Application started with command-line arguments: {}", Arrays.toString(args.getSourceArgs()));
        logger.info("NonOptionArgs: {}", args.getNonOptionArgs());
        logger.info("OptionNames: {}", args.getOptionNames());

        for (String name : args.getOptionNames()){
            logger.info("arg-" + name + "=" + args.getOptionValues(name));
        }

        boolean containsOption = args.containsOption("person.name");
        logger.info("Contains person.name: " + containsOption);
    }
}

but is there anyway to configure the spring-boot app to return the list of mandatory arguments as a -help output when no '--url=https://stackoverflow.com/' argument is provided?

0

There are 0 answers