JCommander integration with SpringBoot
"Because life is too short to parse command line parameters"
-Cédric Beust
JCommander Spring-Boot-Starter will help you to use JCommander with ease.
For more detailed explanation and code samples please consult the home page.
Hello World
-
Add jcommander-spring-boot-starter to your SpringBoot project
<dependency> <groupId>com.etolmach.spring.boot</groupId> <artifactId>jcommander-spring-boot-starter</artifactId> <version>${jcommander.starter.version}</version> </dependency>
-
Define your command parameters bean
@Data @Component @Parameters( commandNames = "greeting", commandDescription = "Say hi to user", separators = "=" ) public class GreetingCommand { @Parameter(names = {"-name", "-n"}, description = "User name", required = true) private String name; @Parameter(names = {"-lang"}, description = "Language") private String topic = "en"; }
For more details consult JCommander guide.
-
Define your command controller bean
@CommandController public class HelloWorldController { private static final String EN_TEMPLATE = "Hello %s!"; private static final String ES_TEMPLATE = "¡Hola %s!"; private static final String RU_TEMPLATE = "Привет %s!"; @CommandHandler(command = "greeting") public void greet( @CommandParameter(name = "-name") String name, @CommandParameter(name = "-lang") String language ) { String template; switch (language){ case "es": template = ES_TEMPLATE; break; case "ru": template = RU_TEMPLATE; break; case "en": default: template = EN_TEMPLATE; } System.out.println(String.format(template, name)); } }
-
Build and run
java -jar hello.jar greeting -name=Jack -lang=es
-
Output
¡Hola Jack!
Configuration
By default the starter automatically listens for command-line arguments on application start-up. You can disable this option by setting parameter:
jcommander.runner.enabled=false
Requirements
- JDK 1.8+
- SpringBoot 2+