Java – Dynamically compiles dependencies according to spring.profiles.active

Dynamically compiles dependencies according to spring.profiles.active… here is a solution to the problem.

Dynamically compiles dependencies according to spring.profiles.active

Can someone guide me where to start this task?

I just need to exclude spring-boot-starter-tomcat when deploying to jboss.

I guess it looks like this :

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web"){
        if(getProperty "spring.profiles.active" == "qat")
            exclude module: "spring-boot-starter-tomcat"
    }
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

For the example above, I get an error :

Could not get unknown property 'spring.profiles.active' for DefaultExternalModuleDependency{group='org.springframework.boot', name='spring-boot-starter-web', version='null', configuration='default'} of type org.gradle.api.internal.artifacts.dependencies.DefaultExternalModuleDependency.

Maybe I can create a custom task to set spring.profiles.active on the task. Help!

Solution

As Peter Ledbrook mentioned, gradle cannot access spring-boot’s application.yml at compile time. And dependencies run early in the gradle lifecycle, and tasks are never invoked until dependencies are resolved.

Even trying dependency resolution strategies is futile.

So I just have to do :

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web") {
        if(System.getProperty("spring.profiles.active") == "qat"){
          exclude module: "spring-boot-starter-tomcat"
        }
    }
    compile("org.springframework.boot:spring-boot-starter-security")
    if(System.getProperty("spring.profiles.active") == "qat"){
        providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
    }
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Then I’ll type gradle build -Dspring-profiles-active=qat when deploying to jboss. and gradle bootRun -Dspring-profiles-active=dev when I have to run locally.

Related Problems and Solutions