Maven or Gradle build types/variants

2019-02-09 19:01发布

问题:

The Android Gradle plugin adds support for build types and build variants, which let you select which version of your application you want to build at the build step (ex, debug or release).

This is a very useful feature for Gradle projects, as you can have 2 versions of your application that may behave differently in some situations, or have different configuration files or properties depending on the type of build.

Now, my question is: is there a similar feature/implementation for non-Android Java projects from Maven or Gradle? I am looking specifically for Java web apps, but I presume the question may have a larger target as well.

回答1:

Cutting it to the chase without vague answers, here is the official response from Luke Daley (Gradleware Engineer) on this matter:

It is something we are actively working on. We are working to support the notion of variants in a general way, so that there will be a consistent approach across domains. It's a deep, deep, change though so there is a lot involved.

You can expect to see aspects of this rolling out in Gradle 2.5 and on.

Later Edit: I've finally been able to get this working on a JavaEE webapp project by using SourceSets instead of Build Types & Variants. Considering that SourceSets have been around for a very very long time, apparently you could've done this ages ago... But not even gradle engineers were able to properly explain how to do so...

Anyhow, check out the build.gradle code below, where we use the same output directory for both SourceSets, then specify the location for the WAR plugin to build from:

apply plugin: 'war'

sourceSets {
    main {
        output.resourcesDir = 'build/resources'
        output.classesDir   = 'build/classes'
    }
    debug {
        java {
            compileClasspath += main.output
            runtimeClasspath += main.output
        }
        output.resourcesDir = 'build/resources'
        output.classesDir   = 'build/classes'
    }
}

task assembleDebugWar(type: War) {
    from sourceSets.debug.output
    archiveName "ROOT.war"
}

task assembleReleaseWar(type: War) {
    from sourceSets.main.output
    archiveName "ROOT.war"
}