Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: overriding one application.property from command line

I have an application.properties file with default variable values. I want to be able to change ONE of them upon running with mvn spring-boot:run. I found how to change the whole file, but I only want to change one or two of these properties.

like image 478
clueless user Avatar asked May 05 '16 14:05

clueless user


People also ask

Can we override application properties in Spring boot?

Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values, properties are considered in the the following order: Command line arguments. Java System properties ( System. getProperties() ).

How do I bypass Spring configuration?

To make a configuration in Spring Boot, you need to create a class and annotate it with @Configuration . Usually, in the configuration class, you can define a beans object. But if you want to override built-in configuration, you need to create a new class that extends the built-in class.


2 Answers

You can pass in individual properties as command-line arguments. For example, if you wanted to set server.port, you could do the following when launching an executable jar:

java -jar your-app.jar --server.port=8081 

Alternatively, if you're using mvn spring-boot:run with Spring boot 2.x:

mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8081" 

Or, if you're using Spring Boot 1.x:

mvn spring-boot:run -Drun.arguments="--server.port=8081" 

You can also configure the arguments for spring-boot:run in your application's pom.xml so they don't have to be specified on the command line every time:

<plugin>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-maven-plugin</artifactId>     <configuration>         <arguments>             <argument>--server.port=8085</argument>         </arguments>     </configuration> </plugin> 
like image 176
Andy Wilkinson Avatar answered Sep 24 '22 12:09

Andy Wilkinson


To update a little things, the Spring boot 1.X Maven plugin relies on the --Drun.arguments Maven user property but the Spring Boot 2.X Maven plugin relies on the -Dspring-boot.run.arguments Maven user property.

So for Spring 2, you need to do :

mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8081" 

And if you need to pass multiple arguments, you have to use , as separator and never use whitespace between arguments :

mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8081,--foo=bar" 

About the the maven plugin configuration and the way of passing the argument from a fat jar, it didn't change.
So the very good Andy Wilkinson answer is still right.

like image 30
davidxxx Avatar answered Sep 25 '22 12:09

davidxxx