1. Overview

While stating of spring boot application requires to pass some command line arguments or application arguments and those arguments require during execution so spring provides the way to access application arguments. Here is an example of Spring boot get application arguments.

org.springframework.boot.ApplicationArguments contains information about arguments source arguments or command line arguments, options arguments and nonoption arguments.

getSourceArgs() method return arguments that were passed to the application. It will return string arrays

getOptionNames() method return then names of all option arguments. For example, if the arguments were “–foo=bar –debug” would return the values [“foo”, “debug”]}

getNonOptionArgs() method eeturn the collection of non-option arguments parsed.

2. Example

@RestController
public class SpringBootExampleController {
    @Autowired
    private org.springframework.boot.ApplicationArguments applicationArguments;
    @RequestMapping("/")
    public String getApplicationArguments() {
        java.util.stream.Stream.of(applicationArguments.getSourceArgs()).forEach(System.out::println);      // it will return command line arguments, It will return String[]
        applicationArguments.getOptionNames().forEach(System.out::println);     // it will return options
        applicationArguments.getNonOptionArgs().forEach(System.out::println);
        return "commandLinePrinted";
    }
}

SpringBootConfig

Make sure that  arguments must need to pass in SpringApplication.run(SpringBootConfig.class, args); method

@SpringBootApplication
@ComponentScan // Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);   // need to pass args in here, Otherwise arguments can not be accessible from org.springframework.boot.ApplicationArguments
    }
}

3. References

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *