使用picocli的可扩展应用程序.最佳实践问题



假设我的项目有很多逻辑,并且有一些入口点,它们是CLI命令。

我用@Command注释入口点,初始化@Parameters@Option注释字段并执行逻辑,这不再需要CLI。

在我看来,为每个@Command带注释的类声明一个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"); }
}

一个例外是,当应用程序具有带子命令的命令时。在这种情况下,您只需要为顶级命令而不是子命令提供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方法。即使有子命令,也不需要工厂。