【问题标题】:Getting Picocli to work with Springboot application让 Picocli 与 Springboot 应用程序一起工作
【发布时间】:2021-07-17 14:55:26
【问题描述】:

我必须将大型 Spring boot 应用程序转换为灵活的 CLI 工具,其中 Spring boot 应用程序发送的请求(除其他外)由命令行中的用户输入确定。我决定使用 picocli 来实现命令行功能,但是如果用户传递给定的选项标志,我什至不知道如何做一些简单的事情,比如将一些文本打印到标准输出,Spring boot 只是像往常一样运行。我应该怎么写这样 picocli 可以与 Spring boot 一起运行(并最终控制所有 Spring boot 的东西)

【问题讨论】:

  • 我可以拥有主要的@SpringBootApplication 实现CommandLineRunner 吗?然后所有commandline 参数都由`void run`处理,还是我定义一个单独的组件作为commandLineRunner,如果有任何命令行参数,spring 会自动计算出应该使用run()?
  • 你看过文档了吗?
  • 是的,在那儿看着它,在问愚蠢的问题之前应该仔细看看。抱歉,到目前为止,我只是一个简单的 C 程序员,我有点不知所措。
  • picocli-spring-boot-starter 也可能有用。甚至可能是必要的。

标签: java spring spring-boot maven picocli


【解决方案1】:

作为对此的跟进,我最终通过将“控制器方法”重构为 3 来使代码正常工作,如下所示:

|
|_ MainApp.java
|_ CmdRunner.java
|_ TheCommand.java

MainApp 是 @SpringBootApplication,基本上就是这样:

System.exit(SpringApplication.exit(new SpringApplication(MainApp.class).run(args)));

开始一切。

CmdRunner是SpringBoot提供的@Component&CommandLineRunner接口的简单实现,最重要的一点如下:

    @Autowired
    private TheCommand theCommand;

    @Override
    public void run(String... args) {
       new CommandLine(theCommand).execute(args);
    }

它在新的 picocli CommandLine 对象上执行传递的 cli 参数(从 MainApp.java 传递给它)。这将我们带到最后一个类,TheCommand.java,它同时是一个 picocli @Command 和 Springboot @Controller 实现 Runnable 接口。而且基本上只包含我需要交付的所有逻辑和(不断增长的)功能。

此实现的唯一缺点是,当用户使用 --help 标志运行它时,应用仍会运行 Spring Boot 内容,使其在特定情况下有点无响应。

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 2012-05-22
    • 2011-04-08
    • 1970-01-01
    • 2011-12-13
    • 2023-04-09
    • 2023-03-04
    • 2020-07-07
    • 2017-06-30
    相关资源
    最近更新 更多