Warm tip: This article is reproduced from serverfault.com, please click

Manage Spring Boot Profiles with Gradle

发布于 2021-02-04 17:11:22

I have a Spring boot application which is managed by Gradle.

What is done so far:

  1. Created application.yaml, application-dev.yaml, and application-qa.yaml files
  2. Mentioned spring: profiles: active: dev in application.yaml (default profile should be dev if none is mentioned)

What need to be done:

  1. Need to build war with profile mentioned or passed while building. Example, for QA build, spring: profiles: active: should have value qa, so that it can pick-up application-qa.yaml properties.
  2. If no profile is passed, then by default dev profile should be selected

What is tried so far:

  1. Added @activeProfiles@ in spring: profiles: active: @activeProfiles@ in application.yaml and added below snippet in build.gradle:

    processResources {
        filter org.apache.tools.ant.filters.ReplaceTokens, tokens: [
            activeProfiles: activeProfiles
        ]
    }
    

    And fired following command to build the war - gradlew clean build -PactiveProfiles=qa, and it just did right job for war file. But now issue with this approach is, how to provide default value for activeProfiles while running the project from IDE (I usually prefer to run main class from IntelliJ)?

I am also not sure if this is the correct approach or is there any other approach to achieve this task. I have already done all these stuff with Maven, and with ease, but I am new to Gradle, and it's project requirement to use Gradle.

Questioner
Jignesh M. Khatri
Viewed
0
Jignesh M. Khatri 2021-02-25 02:17:11

I was able to set default profile, if no profile is passed while running/building the code, using below configurations in build.gradle file. No extra configuration is needed in any IDE to run the project.

def activeProfiles=project.properties['activeProfiles'] ?: "dev" // set default (dev) profile if no profile is passed as property

processResources {
    filter org.apache.tools.ant.filters.ReplaceTokens, tokens: [
        activeProfiles: activeProfiles
    ]
}

I have 3 yaml files for configurations as per environments:

  1. application.yaml
  2. application-dev.yaml
  3. application-qa.yaml

application.yaml contains below configuration for spring profile management, and other common configurations:

spring:
    profiles:
        active: @activeProfiles@
...

application-dev.yaml and application-qa.yaml files contain configurations related to respective environments.