Spring Boot 应用程序很简单:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
System.exit(SpringApplication.exit(
SpringApplication.run(Application.class, args))
);
}
}
CommandLineRunner
并且带有返回值的 Spring Boot也很简单,调用picocli来CommandLine
解析和执行命令:
@Component
public class ApplicationRunner implements CommandLineRunner, ExitCodeGenerator {
private int exitCode;
@Override
public void run(String... args) throws Exception {
exitCode = new CommandLine(new ConnectCommand()).execute(args);
}
@Override
public int getExitCode() {
return exitCode;
}
}
启用picocli的 @-file 支持并使用“标准”选项( ,等)启用帮助和版本信息的ConnectCommand
has :showAtFileInUsageHelp = true
mixinStandardHelpOptions
-h
--help
@Command(
name = "manager",
description = "The manager description",
showAtFileInUsageHelp = true,
mixinStandardHelpOptions = true,
subcommands = {
ListCommand.class,
CreateCommand.class,
DeleteCommand.class
})
@Component
public class ConnectCommand implements Runnable, ExitCodeGenerator {
@Option(
names = {"-u", "--username"},
description = "The username")
private String username;
@Option(
names = {"-p", "--password"},
description = "The password")
private String password;
private int exitCode;
@Override
public void run() {
// WIP: kick-off shell
}
@Override
public int getExitCode() {
return exitCode;
}
}
并且(子)命令都采用这种形式(撒在picocli中@Option
并@Parameters
根据需要):
@Command(
name = "list",
mixinStandardHelpOptions = true,
header = "list stuff")
@Component
class ListCommand implements Runnable{
@Override
public void run() {
System.out.println("listing...");
}
}
有了这个,帮助现在看起来像:
Usage: manager [-hV] [-u=username] [-p=password] [@<filename>...] [COMMAND]
The manager description
[@<filename>...] One or more argument files containing options.
-u, --username=name The username
-p, --password=pass The password
-h, --help Show this help message and exit.
-V, --version Print version information and exit.
Commands:
list list stuff
create create stuff
delete delete stuff
运行单个命令即可:
java -jar manager.jar -u=myname -p=mypass list
listing...
并且运行包含“列表”的@文件也可以:
java -jar manager.jar -u=myname -p=mypass @listing
listing...
这是一个示例存储库。现在我们需要折叠外壳......