问题
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?
回答1:
For each flavour you'll want to
- Create a SourceSet so it will be compiled
- Make the
${flavour}Compile
Configuration extend the maincompile
configuration (see table 45.6 here for the configurations per SourceSet created by the java plugin) - Create a JarTask (using the flavour as a classifier)
- 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'
}
回答2:
I wrote a gradle-java-flavours plugin to do this:
- github project
- JavaFlavoursPlugin.groovy
- JavaFlavoursPluginTest.groovy
来源:https://stackoverflow.com/questions/37279281/how-to-emulate-androids-productflavors-in-a-pure-java-gradle-module