Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting active profile and config location from command line in spring boot

People also ask

How do I select a profile in spring boot?

The solution would be to create more property files and add the "profile" name as the suffix and configure Spring Boot to pick the appropriate properties based on the profile. Then, we need to create three application. properties : application-dev.

How do I change my spring profile at runtime?

You can change property like spring. profile. active at runtime, if you are using config server and refresh the application context. Even then you cannot make sure everthing works, for example, database connections etc.


There are two different ways you can add/override spring properties on the command line.

Option 1: Java System Properties (VM Arguments)

It's important that the -D parameters are before your application.jar otherwise they are not recognized.

java -jar -Dspring.profiles.active=prod application.jar

Option 2: Program arguments

java -jar application.jar --spring.profiles.active=prod --spring.config.location=c:\config

My best practice is to define this as a VM "-D" argument. Please note the differences between spring boot 1.x and 2.x.

The profiles to enable can be specified on the command line:

Spring-Boot 2.x (works only with maven)

-Dspring-boot.run.profiles=local

Spring-Boot 1.x

-Dspring.profiles.active=local

example usage with maven:

Spring-Boot 2.x

mvn spring-boot:run -Dspring-boot.run.profiles=local

Spring-Boot 1.x and 2.x

mvn spring-boot:run -Dspring.profiles.active=local

Make sure to separate them with a comma for multiple profiles:

mvn spring-boot:run -Dspring.profiles.active=local,foo,bar
mvn spring-boot:run -Dspring-boot.run.profiles=local,foo,bar

-Dspring.profiles.active=staging -Dspring.config.location=C:\Config

is not correct.

should be:

--spring.profiles.active=staging --spring.config.location=C:\Config

I had to add this:

bootRun {
    String activeProfile =  System.properties['spring.profiles.active']
    String confLoc = System.properties['spring.config.location']
    systemProperty "spring.profiles.active", activeProfile
    systemProperty "spring.config.location", "file:$confLoc"
}

And now bootRun picks up the profile and config locations.

Thanks a lot @jst for the pointer.


There's another way by setting the OS variable, SPRING_PROFILES_ACTIVE.

for eg :

SPRING_PROFILES_ACTIVE=dev gradle clean bootRun

Reference : How to set active Spring profiles


you can use the following command line:

java -jar -Dspring.profiles.active=[yourProfileName] target/[yourJar].jar