How do I parse command line arguments in Java?

前端 未结 19 1733
终归单人心
终归单人心 2020-11-22 00:16

What is a good way of parsing command line arguments in Java?

19条回答
  •  [愿得一人]
    2020-11-22 00:44

    If you are already using Spring Boot, argument parsing comes out of the box.

    If you want to run something after startup, implement the ApplicationRunner interface:

    @SpringBootApplication
    public class Application implements ApplicationRunner {
    
      public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
      }
    
      @Override
      public void run(ApplicationArguments args) {
        args.containsOption("my-flag-option"); // test if --my-flag-option was set
        args.getOptionValues("my-option");     // returns values of --my-option=value1 --my-option=value2 
        args.getOptionNames();                 // returns a list of all available options
        // do something with your args
      }
    }
    

    Your run method will be invoked after the context has started up successfully.

    If you need access to the arguments before you fire up your application context, you can just simply parse the application arguments manually:

    @SpringBootApplication
    public class Application implements ApplicationRunner {
    
      public static void main(String[] args) {
        ApplicationArguments arguments = new DefaultApplicationArguments(args);
        // do whatever you like with your arguments
        // see above ...
        SpringApplication.run(Application.class, args);
      }
    
    }
    

    And finally, if you need access to your arguments in a bean, just inject the ApplicationArguments:

    @Component
    public class MyBean {
    
       @Autowired
       private ApplicationArguments arguments;
    
       // ...
    }
    

提交回复
热议问题