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]
argv(ARGument Vector) is array of character pointers listing all the arguments. If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will contain pointers to strings. Argv[0] is the name of the program , After that till argv[argc-1] every element is command -line arguments.
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();
      }
}
                        Thanks to the hint of @pvpkiran:
@Component
public class CommandLineHolder implements CommandLineRunner {
    private String[] args;
    @Override
    public void run(String... args) throws Exception {
        this.args = args;
    }
    public String[] getArgs() {
        return args;
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With