Gimme a CLI is a Java library for creating quick and easy command line interfaces (CLIs) using JCommander and Spring's IoC Container.
- JCommander is great for creating command-style CLI argument parsers. Examples of command-style CLIs include git and the AWS CLI.
- Spring's IoC Container provides dependency injection which helps reduce boiler plate and makes it easier to write testable code.
- Gimme a Cli eliminates the tedious setup you would otherwise have to do.
Example starter project can simply be cloned and modified.
-
Define one or more commands for your CLI by implementing the Command interface.
import com.nike.gimme.a.cli.Command; public class HelloWorld implements Command { @Override public void execute() { System.out.println("Hello World!"); } }
Commands are automatically instantiated as Spring beans (e.g. dependencies can be supplied via constructor injection, etc).
-
Optionally use JCommander annotations to define command arguments and options.
import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.nike.gimme.a.cli.Command; @Parameters(commandNames = "hello-world", commandDescription = "Prints \"Hello <name>\" to the terminal") public class HelloWorld implements Command { @Parameter(names = {"--name"}, required = true) private String name; @Override public void execute() { System.out.println("Hello " + name); } }
-
Define a main class and run the GimmeACli program.
import com.nike.gimme.a.cli.Config; import com.nike.gimme.a.cli.GimmeACli; public class Main { public static void main(String[] args) { new GimmeACli( Config.builder() .withCliName("my-cli-name") .withPackagesToScan("com.nike") .build() ).run(args); } }
Spring setup is done for you using classpath scanning.
-
Configure SLF4J logging, e.g.,
- Include logback as a dependency.
dependencies { implementation "ch.qos.logback:logback-classic:1.1.11" }
- Provide a logback.xml.
- Include logback as a dependency.
All of these steps have been done for you in the example starter project which can simply be cloned and modified to fit your needs..
- Global
--help
option gives nicely formatted output.
- JCommander - a library for CLI argument parsing.
- Spring's IoC - a library for easy dependency injection.
- gimme-a-cli-starter-project - An example starter project that can simply be cloned and modified.