Inheriting gradle plugin in subprojects

John Reese picture John Reese · May 5, 2017 · Viewed 8k times · Source

I want to avoid redundancy and therefore I got one "shared" project that contains looks like this:

plugins {
    id "org.flywaydb.flyway" version "4.2.0"
}

repositories {
    mavenCentral()
    jcenter()
}

apply plugin: "java"

dependencies {
    compile "commons-io:commons-io:2.4"

    // ...
}

Then I also have my regular projects that inherit the compile dependencies from my shared project like this:

apply plugin: "java"

repositories {
    mavenCentral()
    jcenter()
}

dependencies {
    compile project(":shared")
    testCompile project(":shared")
}

Is there any way I can make my regular projects inherit the plugin block or the actual plugin as well?

Answer

wasyl picture wasyl · May 5, 2017

Not inherit as such. It seems to me that what you're trying to do can be achieved by configuring the subprojects from the root project. Basically in your root build.gradle (which script that will configure your root project) you can write:

subprojects {
  // configuration
}

You can probably get rid of your shared project and have this in root project's build.gradle:

plugins {
  id "org.flywaydb.flyway" version "4.2.0" apply false
}

subprojects {    
    repositories {
        mavenCentral()
        jcenter()
    }

    apply plugin: "java"
    apply plugin: "org.flywaydb.flyway"

    dependencies {
        compile "commons-io:commons-io:2.4"

        // ...
    }
}

This way all your subprojects will be configured using the same closure - this is equivalent to copy-pasting everything in subprojects block to your individual subprojects' build.gradle files. The advantage over your initial solution is ability to also apply plugins, configure extensions, everything you normally can do.

As a side note, you don't need both jcenter() and mavenCentral in repositories block - jCenter is a superset of mavenCentral and is the preferred one