Home > database >  How can I create two separately configured bootRun tasks using Gradle?
How can I create two separately configured bootRun tasks using Gradle?

Time:11-04

I want to define two different versions of the bootRun task in a Spring boot application using Gradle. This is my attempt, which worked for customizing a single bootRun task. But with multiple tasks containing bootRun, the last bootRun overrides the previous ones.

task local {
  bootRun {
    systemProperty "spring.profiles.active", "dev,postgres"
    jvmArgs "--add-opens=java.base/java.util=ALL-UNNAMED", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
  }
}
local.finalizedBy bootRun

task prod {
  bootRun {
    systemProperty "spring.profiles.active", "postgres"
    jvmArgs "--add-opens=java.base/java.util=ALL-UNNAMED"
  }
}
prod.finalizedBy bootRun

Here, when I run ./gradlew :local, the spring profiles are only postgres. When I comment out the prod task, I get both dev,postgres as expected.

CodePudding user response:

As currently written, your local and prod tasks are default tasks that aren't really doing anything. Your use of bootRun within their configuration is altering the configuration of the existing bootRun task that Spring Boot's Gradle plugin defines.

When you define the tasks, you need to tell Gradle that they are a BootRun task:

task local(type: org.springframework.boot.gradle.tasks.run.BootRun) {
    // …
}

You also need to configure the main class name and the classpath of your new task. You probably want those to be the same as the default bootRun task:

task local(type: org.springframework.boot.gradle.tasks.run.BootRun) {
    mainClass = bootRun.mainClass
    classpath = bootRun.classpath
}

You can then customize the system properties and JVM arguments as you were before. Putting this all together, you can configure your local and prod tasks like this:

task local(type: org.springframework.boot.gradle.tasks.run.BootRun) {
    mainClass = bootRun.mainClass
    classpath = bootRun.classpath
    systemProperty "spring.profiles.active", "dev,postgres"
    jvmArgs "--add-opens=java.base/java.util=ALL-UNNAMED", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005"
}

task prod(type: org.springframework.boot.gradle.tasks.run.BootRun) {
    mainClass = bootRun.mainClass
    classpath = bootRun.classpath
    systemProperty "spring.profiles.active", "postgres"
    jvmArgs "--add-opens=java.base/java.util=ALL-UNNAMED"
}
  • Related