3

I'm trying to set the active spring profile when building a WAR file. I'm building the WAR file with gradle bootWar

I managed to find a solution that works for gradle bootRun -Pprofiles=prod

bootRun {
  if (project.hasProperty('profiles')) {
    environment SPRING_PROFILES_ACTIVE: profiles
  }
}

But

bootWar {
  if (project.hasProperty('profiles')) {
    environment SPRING_PROFILES_ACTIVE: profiles
  }
}

Gives me this error

Could not find method environment() for arguments [{SPRING_PROFILES_ACTIVE=staging}] on task ':bootWar' of type org.springframework.boot.gradle.tasks.bundling.BootWar.

How do I make it work for WAR files?

Snæbjørn
  • 10,322
  • 14
  • 65
  • 124

1 Answers1

4

(Links refer to a demo project in which I do the same you are trying to do right now, but with some extra complexity, read first the property, etc. and set different profiles as active: development, testing, production and some other SO posts)


Suppose we want to set the active profile as production.

In the build.gradle you could create a task which writes the property spring.profiles.active using the ant.propertyfile like this:

task setProductionConfig() {
    group = "other"
    description = "Sets the environment for production mode"
    doFirst {
        /*
           notice the file location ("./build/resources/main/application.properties"),
           it refers to the file processed and already in the build folder, ready
           to be packed, if you use a different folder from `build`, put yours
           here
        */
        ant.propertyfile(file: "./build/resources/main/application.properties") {
            entry(key: "spring.profiles.active", value: "production")
        }
    }
    doLast {
        // maybe put some notifications in console here
    }
}

Then you tell the bootWar task it depends on this previous task we made like this:

bootWar {
    dependsOn setProductionConfig
}
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80