Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access command line args in a spring bean?

Tags:

java

spring

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]

like image 664
membersound Avatar asked May 09 '17 08:05

membersound


People also ask

How do you read a command-line argument?

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.


2 Answers

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();

      }
}
like image 123
Olivier Boissé Avatar answered Sep 25 '22 15:09

Olivier Boissé


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;
    }
}
like image 43
membersound Avatar answered Sep 22 '22 15:09

membersound