Passing Command Line Arguments in Java – Spring Boot Example

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

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

In above example our Spring Boot Application is implementing 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 program will be treated as Non Option Arguments. Lets 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 is one of the approach taken to externalize your application configuration. Spring Boot supports such many approaches and has strict precedence order to allow sensible overriding of values. In our case if any property is defined in application properties and similar option name is passed via command line, then 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 app.property on command line we will see below output

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 *