[java] how to use Spring Boot profiles

i have application.yml,application-dev.ymlandapplication-dev.yml

  1. I'm using the maven command mvn spring-boot:run -Dspring.profiles.active=dev it doesn't work and I can not choose the dev profile using mvn spring-boot:run. How do I choose it?
  2. The documentation says java -jar XXX.jar --spring.profiles.active=dev works, and I tried -Dspring.profiles.active=dev but it does not work. And in my project, i use java -jar XXX.jar it runs, but if I use java -jar XXX.jar --spring.profiles.active=dev to choose dev profile, console print so many logs and warns that i never see used java -jar XXX.jar,and tell me APPLICATION FAILED TO START

so how to solve two problems? thanks~

This question is related to java spring spring-boot

The answer is


If your using maven,

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <profiles>
                        <profile>dev</profile>
                    </profiles>
                </configuration>
            </plugin>
        </plugins>
    </build>

this set dev as active profile

./mvnw spring-boot:run

will have dev as active profile.


If you are using the Spring Boot Maven Plugin, run:

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

(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)


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

**Source- **https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html

Basically it is need when you multiple application-{environment}.properties is present inside in your project. by default, if you passed -Drun.profiles on command line or activeByDefault true in

 <profile>
    <id>dev</id>
    <properties>
        <activatedProperties>dev</activatedProperties>
    </properties>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
</profile>

Nothing defined like above it will choose by default application.properties otherwise you need to select by appending -Drun.profiles={dev/stage/prod}.

TL;DR

mvn spring-boot:run -Drun.profiles=dev


You can specify properties according profiles in one application.properties(yml) like here. Then mvn clean spring-boot:run -Dspring.profiles.active=dev should run it correct. It works for me


Create specific .yml files in the resources directory for each and every environment(Eg: dev,qa,stg etc.) that you need to run the application. image of .yml files in resources directory

If you are using spring-boot-maven-plugin 2.0.5.RELEASE in your pom.xml file you can add the profiles within the dependency tag as follows. image of pom.xml spring-boot-maven-plugin (you can configure multiple profiles using multiple profile tags)

Then you can use the following commands to build and run the project.

1) mvn clean install
2) mvn spring-boot:run -Dspring-boot.run.default==qa

Then you will see that the default profile is set as qa while running the project. displaying the default profile when running the application


If you are using maven, define your profiles as shown below within your pom.xml

<profiles>
<profile>
    <id>local</id>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
    <properties>
        <jdbc.url>dbUrl</jdbc.url>
        <jdbc.username>dbuser</jdbc.username>
        <jdbc.password>dbPassword</jdbc.password>
        <jdbc.driver>dbDriver</jdbc.driver>
    </properties>
</profile>
<profile>
    <id>dev</id>
    <properties>
        <jdbc.url>dbUrl</jdbc.url>
        <jdbc.username>dbuser</jdbc.username>
        <jdbc.password>dbPassword</jdbc.password>
        <jdbc.driver>dbDriver</jdbc.driver>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
        </dependency>
    </dependencies>
</profile>
<profile>
    <id>prod</id>
    <properties>
        <jdbc.url>dbUrl</jdbc.url>
        <jdbc.username>dbuser</jdbc.username>
        <jdbc.password>dbPassword</jdbc.password>
        <jdbc.driver>dbDriver</jdbc.driver>
    </properties>
</profile>

By default, i.e if No profile is selected, the local profile will always be use.

To select a specific profile in Spring Boot 2.x.x, use the below command.

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

If you want want to build/compile using properties of a specific profile, use the below command.

mvn clean install -Pdev -DprofileIdEnabled=true

Since Spring Boot v2+

I have verified with Spring Boot v2.3.5.RELEASE

With Spring Boot Maven Plugin

You can provide commandline argument like this:

mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=dev"

You can provide JVM argument like this:

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

java -jar

java -Dspring.profiles.active=dev -jar app.jar (Note order)

or

java -jar app.jar --spring.profiles.active=dev (Note order)


Working with Intellij, because I don't know how to set keyboard shortcut to mvn spring-boot:run -Dspring.profiles.active=dev, I have to do this:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>
            -Dspring.profiles.active=dev
        </jvmArguments>
    </configuration>
</plugin>

I'm not sure I fully understand the question but I'll attempt to answer by providing a few details about profiles in Spring Boot.

For your #1 example, according to the docs you can select the profile using the Spring Boot Maven plugin using -Drun.profiles.

Edit: For Spring Boot 2.0+ run has been renamed to spring-boot.run and run.profiles has been renamed to spring-boot.run.profiles

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

https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/maven-plugin/examples/run-profiles.html

From your #2 example, you are defining the active profile after the name of the jar. You need to provide the JVM argument before the name of the jar you are running.

java -jar -Dspring.profiles.active=dev XXX.jar

General info:

You mention that you have both an application.yml and a application-dev.yml. Running with the dev profile will actually load both config files. Values from application-dev.yml will override the same values provided by application.yml but values from both yml files will be loaded.

There are also multiple ways to define the active profile.

You can define them as you did, using -Dspring.profiles.active when running your jar. You can also set the profile using a SPRING_PROFILES_ACTIVE environment variable or a spring.profiles.active system property.

More info can be found here: https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-set-active-spring-profiles


Alternatively, the profile can be directly specified in the application.properties file by adding the line:

spring.profiles.active=prod

Profiles work in conjunction with Spring Boot properties files. By default, Spring Boot parses a file called application.properties – located in the src/main/resources directory – to identify configuration information.

Our first task will be to add a parameter in that file which will tell Spring to use a different environment-specific property file corresponding to the active profile (i.e. the profile that the app is currently being run with). We can do this by adding the following to the application.properties file:

spring.profiles.active=@activatedProperties@

Now we need to create the two new environment-specific property files (in the same path as the existing application.properties file), one to be used by the DEV profile and one to be used by the PROD profile. These files need to be named the following:

application-dev.properties

application-prod.properties

In each case, we specify prod as the active profile, which causes the application-prod.properties file to be chosen for configuration purposes.


Use "-Dspring-boot.run.profiles=foo,local" in Intellij IDEA. It's working. Its sets 2 profiles "foo and local".

Verified with boot version "2.3.2.RELEASE" & Intellij IDEA CE 2019.3.

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Setting profile with "mvn spring-boot:run" enter image description here

Setting environment variable enter image description here


You don't need three .yml files for this. You can have a single application.yml file and write profile specific properties in the same where each profile section is separated by 3 hyphen (---)

Next, for selecting the current active profile, you can specify that as well in your application.yml file, like this :

spring:
  profiles:
    active:
    - local

However, this configuration will be overriden if you set an Environment variable, eg : SPRING_PROFILES_ACTIVE = dev


Here is a sample file for you requirement:

# include common properties for every profile in this section

server.port: 5000 

spring:
  profiles:
    active:
    - local

---
# profile specific properties

spring:
  profiles: local

  datasource:
    url: jdbc:mysql://localhost:3306/
    username: root
    password: root

---
# profile specific properties

spring:
  profiles: dev

  datasource:
    url: jdbc:mysql://<dev db url>
    username: <username>
    password: <password>

The @Profile annotation allows you to indicate that a component is eligible for registration when one or more specified profiles are active. Using our example above, we can rewrite the dataSource configuration as follows:

@Configuration
@Profile("dev")
public class StandaloneDataConfig {

    @Bean
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("classpath:com/bank/config/sql/schema.sql")
            .addScript("classpath:com/bank/config/sql/test-data.sql")
            .build();
    }
}

And other one:

@Configuration
@Profile("production")
public class JndiDataConfig {

    @Bean(destroyMethod="")
    public DataSource dataSource() throws Exception {
        Context ctx = new InitialContext();
        return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
    }
}

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 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