In this short Spring Boot tutorial, you will learn how to pass command-line arguments to your Spring Boot application.
Passing Command-Line Arguments
To pass command line arguments to your Spring Boot app when running it with Maven use the -Dspring-boot.run.arguments.
In the below code example, I will pass two command-line arguments: firstName and lastName.
mvn spring-boot:run -Dspring-boot.run.arguments="--firstName=Sergey --lastName=Kargopolov"
or
mvn package java -jar target/<FILENAME.JAR HERE> --firstName=Sergey --lastName=Kargopolov
Reading Command-Line Arguments
You can read command-line arguments just like you do it in any Java application. In your Spring Boot project find a Java class that contains the public static void main(String[] args) method and read command-line arguments there in the following way:
package com.appsdeveloperblog.examples.commandlinearguments; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CommandLineArgumentsExampleApplication { public static void main(String[] args) { // Reading Command-Line arguments for(String arg:args) { System.out.println(arg); } SpringApplication.run(CommandLineArgumentsExampleApplication.class, args); } }
Update application.properties Values
You can use Command-Line arguments to update values in your application.properties file when starting your Spring Boot application. For example, in you application.properties file, you can set the server port number to be initially 8080 and then use Command-Line argument to override this value to a different port number.
Default Values in application.properties File
server.port=8080
Overwrite port number using Command-Line argument:
mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8081
or
mvn package java -jar target/<FILENAME.JAR HERE> --server.port=8081
I hope this very short Spring Boot tutorial was of some help to you.
To learn more about Spring Boot have a look at the list of below video courses. One of them, might be what you need and will help you take your skills to a new level.
In my eclipse launch for Maven:
spring-boot:run -Dspring-boot.run.arguments=–firstName=Sergey,–lastName=Kargopolov
Only had one arg with “Sergey,–lastName=Kargopolov” as the value.
I had to use:
spring-boot:run -Dspring-boot.run.arguments=”–firstName=Sergey –lastName=Kargopolov”