How to access command line args in a spring bean?

java, spring

Solution

By analyzing spring source code, it seems that spring registers a singleton bean of type `ApplicationArguments` in the method `prepareContext` of the class `SpringApplication`

context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);

So I think you can autowire this bean in your service :

@Component
public MyService {

      @Autowired
      private ApplicationArguments  applicationArguments;

      public void run() {
             //read varargs
             applicationArguments.getSourceArgs();

      }
}

Problem

Question: how can I access the `varargs` of the startup method inside a spring `@Bean` like MyService below? ``` @SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } @Component public MyService { public void run() { //read varargs } } ``` java -jar [jarfile] [Command Line Arguments]

Original source