2

我正在尝试使用 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.
4

1 回答 1

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中有一个类似的例子 。

于 2021-09-11T01:58:52.673 回答