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

Scalable applications with picocli. Best practice question

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

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

在我看来,我适合为每个 @Command 注释 class 声明 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"); }
}

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