2

I am trying to create a spring boot CLI App using picocli. I followed the steps as mentioned in the tutorial, but when I start the service the whole flow runs. What I want is to call the command from the terminal then only the flow should trigger.Can anyone please help me resolving this. Below is my code.

Component class

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.
SS12345
  • 21
  • 3

1 Answers1

2

If you want to add command line parsing to Spring Boot's external configuration in the @SpringBootApplication, do something like (see 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.
         */
    }
}

There is a similar example in Install.java.

Allen D. Ball
  • 1,916
  • 1
  • 9
  • 16