【问题标题】:Picocli Spring boot CLI ApplicationPicocli Spring Boot CLI 应用程序
【发布时间】:2021-11-07 05:38:10
【问题描述】:

我正在尝试使用 picocli 创建一个 Spring Boot CLI 应用程序。我按照教程中提到的步骤进行操作,但是当我启动服务时,整个流程都会运行。 我想要的是从终端调用命令,然后只有流程应该触发。谁能帮我解决这个问题。 下面是我的代码。

组件类

public class AppCLI implements CommandLineRunner {

    @Autowired
    AppCLI appCLI;

    public String hello(){
        return "hello";
    }

    @CommandLine.Command(name = "command")
    public void command() {
        System.out.println("Adding some files to the staging area");
    }

    @Override
    public void run(String... args) throws Exception {
        CommandLine commandLine = new CommandLine(appCLI);
        commandLine.parseWithHandler(new CommandLine.RunLast(), args);
        System.out.println("In the main method");
        hello();
        command();
    }
}

Command class

@Controller
@CommandLine.Command(name = "xyz",description = "Performs ", mixinStandardHelpOptions = true, version = "1.0")
public class AppCLI implements Runnable{
    @Override
    public void run() {
        System.out.println("Hello");
    }
}

Main Class

@SpringBootApplication
public class Application {

    private static Logger LOG = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


}

Thanks in advance.

【问题讨论】:

    标签: spring-boot command-line-interface picocli


    【解决方案1】:

    如果你想在 Spring Boot 的外部添加命令行解析 @SpringBootApplication 中的配置,执行类似的操作(参见 Connect.java):

    import picocli.CommandLine.Command;
    import picocli.CommandLine.Option;
    import picocli.CommandLine;
    
    @SpringBootApplication
    @Command
    @NoArgsConstructor @ToString @Log4j2
    public class Connect implements ApplicationRunner {
        @Option(description = { "connection_file" }, names = { "-f" }, arity = "1")
        @Value("${connection-file:#{null}}")
        private String connection_file = null;
    
        @Override
        public void run(ApplicationArguments arguments) throws Exception {
            new CommandLine(this)
                .setCaseInsensitiveEnumValuesAllowed(true)
                .parseArgs(arguments.getNonOptionArgs().toArray(new String [] { }));
            /*
             * Command implementation; command completes when this method
             * completes.
             */
        }
    }
    

    有一个类似的例子 Install.java.

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 2019-08-31
      • 2016-03-08
      • 2020-12-21
      • 2015-03-25
      • 2018-01-10
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      相关资源
      最近更新 更多