假设我的项目执行大量逻辑,并且有一些入口点,它们是 CLI 命令。
我用@Command
注释我的入口点,初始化我的@Parameters
和@Option
注释字段并执行逻辑,这并不不再需要 CLI。
据我所知,为每个 @Command
带注释的类声明 1 个 main
方法比较适合我,但是,我不确定这是否是一个好主意。
也许某种CommandFactory
是必要的?
我以前从未构建过 CLI 应用程序或使用过 picocli,因此如果我的思维过程有误,请指出。
最佳答案
对于作为入口点的每个 @Command
来说,有一个单独的 main
方法是完全可以的。需要 main
方法,以便可以从命令行独立调用该命令。
例如:
@Command(name = "hello")
class Hello implements Runnable {
public static void main(String[] args) {
CommandLine.run(new Hello(), args);
}
public void run() { System.out.println("hello"); }
}
@Command(name = "bye")
class Bye implements Runnable {
public static void main(String[] args) {
CommandLine.run(new Bye(), args);
}
public void run() { System.out.println("bye"); }
}
一个异常(exception)是当您的应用程序具有 subcommands 的命令时。在这种情况下,您只需要为顶级命令使用 main
方法,而不需要为子命令使用 main
方法。
带有子命令的示例:
@Command(name = "git", subcommands = {Commit.class, Status.class})
class Git implements Runnable {
public static void main(String[] args) { // top-level command needs main
CommandLine.run(new Git(), args);
}
public void run() { System.out.println("Specify a subcommand"); }
}
@Command(name = "commit")
class Commit implements Runnable {
@Option(names = "-m") String message;
@Parameters File[] files;
public void run() {
System.out.printf("Committing %s with message '%s'%n",
Arrays.toString(files), message);
}
}
@Command(name = "status")
class Status implements Runnable {
public void run() { System.out.println("All ok."); }
}
请注意,当有子命令时,只有顶级命令需要 main
方法。
即使使用子命令,也不需要工厂。
关于java - 使用 picocli 可扩展的应用程序。最佳实践问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53188689/