[java] How to run bootRun with spring profile via gradle task

I'm trying to set up gradle to launch the bootRun process with various spring profiles enabled.

My current bootRun configuration looks like:

bootRun {
    // pass command line options from gradle to bootRun
    // usage: gradlew bootRun "-Dspring.profiles.active=local,protractor"
    if (System.properties.containsKey('spring.profiles.active')) {
        systemProperty "spring.profiles.active", System.properties['spring.profiles.active']
    }
}

I'd like to set system properties with a gradle task, and then execute bootRun.

My attempt looked like this:

task bootRunDev

bootRunDev  {
    System.setProperty("spring.profiles.active", "Dev")
}

A few questions:

  1. is systemProperty a part of the spring boot bootRun configuration?
  2. is it possible to set a system property in another task?
  3. What should my next step be? I need to get bootRunDev configuration to happen before bootRun
  4. Is there another approach I should look into

-Eric

This question is related to java spring gradle

The answer is


Simplest way would be to define default and allow it to be overridden. I am not sure what is the use of systemProperty in this case. Simple arguments will do the job.

def profiles = 'prod'

bootRun {
  args = ["--spring.profiles.active=" + profiles]
}

To run dev:

./gradlew bootRun -Pdev

To add dependencies on your task you can do something like this:

task setDevProperties(dependsOn: bootRun) << {
  doFirst {
    System.setProperty('spring.profiles.active', profiles)
  }
}

There are lots of ways achieving this in Gradle.

Edit:

Configure separate configuration files per environment.

if (project.hasProperty('prod')) {
  apply from: 'gradle/profile_prod.gradle'
} else {
  apply from: 'gradle/profile_dev.gradle'
}

Each configuration can override tasks for example:

def profiles = 'prod'
bootRun {
  systemProperty "spring.profiles.active", activeProfile
}

Run by providing prod flag in this case just like that:

./gradlew <task> -Pprod

Configuration for 4 different task with different profiles and gradle tasks dependencies:

  • bootRunLocal and bootRunDev - run with specific profile
  • bootPostgresRunLocal and bootPostgresRunDev same as prev, but executing custom task runPostgresDocker and killPostgresDocker before/after bootRun

build.gradle:

final LOCAL='local'
final DEV='dev'

void configBootTask(Task bootTask, String profile) {
    bootTask.main = bootJar.mainClassName
    bootTask.classpath = sourceSets.main.runtimeClasspath

    bootTask.args = [ "--spring.profiles.active=$profile" ]
//    systemProperty 'spring.profiles.active', profile // this approach also may be used
    bootTask.environment = postgresLocalEnvironment
}

bootRun {
    description "Run Spring boot application with \"$LOCAL\" profile"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunLocal(type: BootRun, dependsOn: 'classes') {
    description "Alias to \":${bootRun.name}\" task: ${bootRun.description}"
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootRunDev(type: BootRun, dependsOn: 'classes') {
    description "Run Spring boot application with \"$DEV\" profile"
    doFirst() {
        configBootTask(it, DEV)
    }
}

task bootPostgresRunLocal(type: BootRun) {
    description "Run Spring boot application with \"$LOCAL\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, LOCAL)
    }
}

task bootPostgresRunDev(type: BootRun) {
    description "Run Spring boot application with \"$DEV\" profile and re-creating DB Postgres container"
    dependsOn runPostgresDocker
    finalizedBy killPostgresDocker
    doFirst() {
        configBootTask(it, DEV)
    }
}

For anyone looking how to do this in Kotlin DSL, here's a working example for build.gradle.kts:

tasks.register("bootRunDev") {
    group = "application"
    description = "Runs this project as a Spring Boot application with the dev profile"
    doFirst {
        tasks.bootRun.configure {
            systemProperty("spring.profiles.active", "dev")
        }
    }
    finalizedBy("bootRun")
}

Environment variables can be used to set spring properties as described in the documentation. So, to set the active profiles (spring.profiles.active) you can use the following code on Unix systems:

SPRING_PROFILES_ACTIVE=test gradle clean bootRun

And on Windows you can use:

SET SPRING_PROFILES_ACTIVE=test
gradle clean bootRun

Kotlin edition: Define the following task in you build.gradle.kts file:

tasks.named<BootRun>("bootRun") {
  args("--spring.profiles.active=dev")
}

This will pass the parameter --spring.profiles.active=dev to bootRun, where the profile name is dev in this case.

Every time you run gradle bootRun the profile dev is used.


Using this shell command it will work:

SPRING_PROFILES_ACTIVE=test gradle clean bootRun

Sadly this is the simplest way I have found. It sets environment property for that call and then runs the app.


Add to VM options: -Dspring.profiles.active=dev

Or you can add it to the build.gradle file to make it work: bootRun.systemProperties = System.properties.


Spring Boot v2 Gradle plugin docs provide an answer:

6.1. Passing arguments to your application

Like all JavaExec tasks, arguments can be passed into bootRun from the command line using --args='<arguments>' when using Gradle 4.9 or later.

To run server with active profile set to dev:

$ ./gradlew bootRun --args='--spring.profiles.active=dev'

In your build.gradle file simply use the following snippet

bootRun {
  args = ["--spring.profiles.active=${project.properties['profile'] ?: 'prod'}"]
}

And then run following command to use dev profile:

./gradlew bootRun -Pprofile=dev

my way:

in gradle.properties:

profile=profile-dev

in build.gradle add VM options -Dspring.profiles.active:

bootRun {
   jvmArgs = ["-Dspring.output.ansi.enabled=ALWAYS","-Dspring.profiles.active="+profile]
}

this will override application spring.profiles.active option


For those folks using Spring Boot 2.0+, you can use the following to setup a task that will run the app with a given set of profiles.

task bootRunDev(type: org.springframework.boot.gradle.tasks.run.BootRun, dependsOn: 'build') {
    group = 'Application'

    doFirst() {
        main = bootJar.mainClassName
        classpath = sourceSets.main.runtimeClasspath
        systemProperty 'spring.profiles.active', 'dev'
    }
}

Then you can simply run ./gradlew bootRunDev or similar from your IDE.


I wanted it simple just to be able to call gradle bootRunDev like you without having to do any extra typing..

This worked for me - by first configuring it the bootRun in my task and then right after it running bootRun which worked fine for me :)

task bootRunDev {
    bootRun.configure {
        systemProperty "spring.profiles.active", 'Dev'
    }
}

bootRunDev.finalizedBy bootRun

For someone from internet, there was a similar question https://stackoverflow.com/a/35848666/906265 I do provide the modified answer from it here as well:

// build.gradle
<...>

bootRun {}

// make sure bootRun is executed when this task runs
task runDev(dependsOn:bootRun) {
    // TaskExecutionGraph is populated only after 
    // all the projects in the build have been evaulated https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html#whenReady-groovy.lang.Closure-
    gradle.taskGraph.whenReady { graph ->
        logger.lifecycle('>>> Setting spring.profiles.active to dev')
        if (graph.hasTask(runDev)) {
            // configure task before it is executed
            bootRun {
                args = ["--spring.profiles.active=dev"]
            }
        }
    }
}

<...>

then in terminal:

gradle runDev

Have used gradle 3.4.1 and spring boot 1.5.10.RELEASE


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)