Friday, September 21, 2018

Parsing command line arguments in Spring etc

lots of frameworks are reported here:
https://stackoverflow.com/questions/367706/how-do-i-parse-command-line-arguments-in-java/


but eventually I just want to do it using Spring classes

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/SimpleCommandLinePropertySource.html

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/JOptCommandLinePropertySource.html

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

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/core/env/CommandLinePropertySource.html



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;


@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

 public static void main(String[] args) {
  SpringApplication.run(DemoApplication.class, args);
 }

 @Override
 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 https://projects.spring.io/spring-shell/ project, but only to write CLI applications







No comments: