Passing Command Line Arguments in Java – Spring Boot Example

Application properties are part of each and every application. To make your project robust and easy for the configuration you always think of keeping some properties either in the file, database or you can pass them as Command Line Arguments in Java. In this small article, we will quickly look into how you can leverage Spring Boot and its capabilities.

Command Line Arguments in Java – Spring Boot Example

By default, Spring comes with inbuilt options parser in the form of the ApplicationArguments interface.  This interface will make sure that all you get to access command line parameters easily. By default, all command line parameters that start with — are converted to options. We will see the same using a simple example.

In the above example, our Spring Boot Application is implementing the ApplicationRunner interface. With this interface, we must implement the run method to which we can pass command-line arguments as ApplicationArguments. Once we have access to arguments you can iterate over them and process. Every command-line argument with format

is converted to Option Name and Option Value. All other parameters passed to the program will be treated as Non Option Arguments. Let’s run the above program with below command-line arguments

And here is the output (after removing unnecessary console log)

As usual Spring Boot has made the development easy and enjoyable.

Command Line Arguments Precedence

Passing command-line arguments in java is one of the approaches taken to externalize your application configuration. Spring Boot supports such many approaches and has strict precedence in order to allow sensible overriding of values. In our case, if any property is defined in application properties and a similar option name is passed via command line, then the value from application properties will be overwritten.

You can find complete precedence order in Spring Official Documentation.

Lets test this precedence. Below is our properties file

We will add a simple rest controller to output our property from Spring Environment.

and when we run our application with and without on command line we will see below

output:Command Line Arguments in Java


I hope you find this example useful and do not hesitate to ask questions or comment.

Add a Comment

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