spring-boot-command-line-arguments
Command-Line Arguments in Spring Boot
1. Overview
In this quick tutorial, we’ll discuss how to pass command-line arguments to a Spring Boot application.
We can use command-line arguments to configure our application, override application properties or pass custom arguments.
2. Maven Command-Line Arguments
Later, we’ll see how to access the arguments in our code.
2.1. Spring Boot 1.x
mvn spring-boot:run -Drun.arguments=--customArgument=custom
We can also pass multiple parameters to our app:
mvn spring-boot:run -Drun.arguments=--spring.main.banner-mode=off,--customArgument=custom
Note that:
-
Arguments should be comma separated
-
Each argument should be prefixed with —
-
We can also pass configuration properties, like spring.main.banner-mode shown in the example above
3. Gradle Command-Line Arguments
We’ll need to configure our bootRun task in build.gradle file:
bootRun {
if (project.hasProperty('args')) {
args project.args.split(',')
}
}
Now, we can pass the command-line arguments as follows:
./gradlew bootRun -Pargs=--spring.main.banner-mode=off,--customArgument=custom
4. Overriding System Properties
For example, here’s our application.properties file:
server.port=8081
spring.application.name=SampleApp
To override the server.port value, we need to pass the new value in the following manner (for Spring Boot 1.x):
mvn spring-boot:run -Drun.arguments=--server.port=8085
Similarly for Spring Boot 2.x:
mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085
Note that:
-
Spring Boot converts command-line arguments to properties and adds them as environment variables
-
We can use short command-line arguments –port=8085 instead of –server.port=8085 by using a placeholder in our application.properties:
server.port=${port:8080}
-
Command-line arguments take precedence over application.properties values
If needed, we can stop our application from converting command-line arguments to properties:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(Application.class);
application.setAddCommandLineProperties(false);
application.run(args);
}
}
5. Accessing Command-Line Arguments
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
for(String arg:args) {
System.out.println(arg);
}
SpringApplication.run(Application.class, args);
}
}
This will print the arguments we passed to our application from command-line, but we could also use them later in our application.