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

I have a spring boot application.

I have three profiles in my application-> development, staging and production. So I have 3 files

  1. application-development.yml
  2. application-staging.yml
  3. application-production.yml

My application.yml resides inside src/main/resources. I have set the active profile in application.yml as :

spring:
  profiles.active: development

The other 3 profile specific config files are present in C:\config folder.

I am using gradle plugin for eclipse. When I try to do a "bootRun", I am setting the command line arguments in my gradle configuration in eclipse as

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

However, the command line property is not getting reflected and my active profile is always getting set as development(which is the one that I have mentioned in the applications.yml file). Also C:\Config folder is not searched for profile specific config files.

I think I am missing something here. I have been trying to figure it out for the past 2 days. But no luck. I would really appreciate any help.

This question is related to java spring gradle spring-boot yaml

The answer is


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.


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

is not correct.

should be:

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

A way that i do this on intellij is setting an environment variable on the command like so:

test setup on intellij

In this case i am setting the profile to test


Michael Yin's answer is correct but a better explanation seems to be required!

A lot of you mentioned that -D is the correct way to specify JVM parameters and you are absolutely right. But Michael is also right as mentioned in Spring Boot Profiles documentation.

What is not clear in the documentation, is what kind of parameter it is: --spring.profiles.active is a not a standard JVM parameter so if you want to use it in your IDE fill the correct fields (i.e. program arguments)


I think your problem is likely related to your spring.config.location not ending the path with "/".

Quote the docs

If spring.config.location contains directories (as opposed to files) they should end in / (and will be appended with the names generated from spring.config.name before being loaded).

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-application-property-files


If you use Gradle:

-Pspring.profiles.active=local

When setting the profile via the Maven plugin you must do it via run.jvmArguments

mvn spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=production"

With debug option:

mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 -Dspring.profiles.active=jpa"

I've seen this trip a lot of people up..hope it helps


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

We want to automatically pick property file based upon mentioned the profile name in spring.profiles.active and the path in -Dspring.config.location

application-dev.properties

If we are running jar in Unix OS then we have to use / at the end of -Dspring.config.location otherwise it will give below error.

Error :: java.lang.IllegalStateException: File extension of config file location 'file:/home/xyz/projectName/cfg' is not known to any PropertySourceLoader. If the location is meant to reference a directory, it must end in '/'

Example

java -Dspring.profiles.active=dev -Dspring.config.location=/home/xyz/projectName/cfg/ -jar /home/xyz/project/abc.jar

or

java -jar /home/xyz/project/abc.jar --spring.profiles.active=dev --spring.config.location=/home/xyz/projectName/cfg/

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to spring-boot

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Why am I getting Unknown error in line 1 of pom.xml? Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured How to resolve Unable to load authentication plugin 'caching_sha2_password' issue ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName ERROR Source option 1.5 is no longer supported. Use 1.6 or later How to start up spring-boot application via command line? JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Examples related to yaml

Use placeholders in yaml How to test that a registered variable is not empty? YAML equivalent of array of objects in JSON How to set multiple commands in one yaml file with Kubernetes? Mapping list in Yaml to list of objects in Spring Boot YAML mapping values are not allowed in this context Setting active profile and config location from command line in spring boot Using Docker-Compose, how to execute multiple commands Check if a list contains an item in Ansible Converting Swagger specification JSON to HTML documentation