Friday, September 21, 2018

Parsing command line arguments in Spring etc

lots of frameworks are reported here:

but eventually I just want to do it using Spring classes

The advantage in Spring is that you can directly bind the command line arguments to attributes, there is an example here

A very simple example:

package org.pierre.clidemo;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.SimpleCommandLinePropertySource;
import org.springframework.boot.CommandLineRunner;

public class DemoApplication implements CommandLineRunner {

 public static void main(String[] args) {, args);

 public void run(String... args) throws Exception {
  PropertySource ps = new SimpleCommandLinePropertySource(args);
  // --file=pippo.txt --language=EN_TO_DE --firstOriginal=true
  System.out.println("file=" + ps.getProperty("file"));
  System.out.println("language=" + ps.getProperty("language"));
  System.out.println("firstOriginal=" + ps.getProperty("firstOriginal"));

and of course the JOptCommandLinePropertySource version is more robust...

Interesting also the project, but only to write CLI applications

No comments: