简体   繁体   中英

How to emulate Android's productFlavors in a pure java gradle module?

I need three flavors:

  • fake
  • staging
  • prod

fake will provide classes like FakeUser , FakeUserDb - it's very important that these classes are not compiled into the prod flavor.

prod and staging are completely identical, except that I need to compile a different String url into prod vs staging .

So, I need to create an "abstract" real flavor that both prod and staging inherit.

This can be easily done with the android gradle plugin, but how can I do it in a pure java gradle module?

For each flavour you'll want to

  1. Create a SourceSet so it will be compiled
  2. Make the ${flavour}Compile Configuration extend the main compile configuration (see table 45.6 here for the configurations per SourceSet created by the java plugin)
  3. Create a JarTask (using the flavour as a classifier)
  4. Publish the jar artifact so the flavour can be referenced via the classifier

Something like:

def flavours = ['fake', 'staging', 'prod']
flavours.each { String flavour ->
    SourceSet sourceSet = sourceSets.create(flavour)
    sourceSet.java {
       srcDirs 'src/main/java', "src/$flavour/java"
    }
    sourceSet.resources {
       srcDirs 'src/main/resources', "src/$flavour/resources"
    }
    Task jarTask = tasks.create(name: "${flavour}Jar", type: Jar) {
       from sourceSet.output
       classifier flavour
    }
    configurations.getByName("${flavour}Compile").extendsFrom configurations.compile
    configurations.getByName("${flavour}CompileOnly").extendsFrom configurations.compileOnly
    configurations.getByName("${flavour}CompileClasspath").extendsFrom configurations.compileClasspath
    configurations.getByName("${flavour}Runtime").extendsFrom configurations.runtime

    artifacts {
       archives jarTask
    }
    assemble.dependsOn jarTask
}

Then, to reference one of the flavours in another project you could do one of the following:

dependencies {
   compile project(path: ':someProject', configuration: 'fakeCompile')
   compile project(path: ':someProject', configuration: 'fakeRuntime')
   compile 'someGroup:someProject:1.0:fake'
   compile group: 'someGroup', name: 'someProject', version: '1.0', classifier: 'fake'
}

I wrote a gradle-java-flavours plugin to do this:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM