How to set a dependency for a project with all subprojects?
Asked Answered
A

2

9

I don't like that I repeat every repository dependency (let us say, junit), for the main project and for subprojects. Is there a possibility to make the subproject to use the dependencies of the main project. Or is there another way to escape that repetition?

Accept answered 26/1, 2017 at 14:1 Comment(0)
I
6

root/build.gradle

allprojects {
    if (plugins.hasPlugin('java')) {
        dependencies {
            testCompile 'junit:junit:4.12'
        }
    }
}
Inflexed answered 26/1, 2017 at 14:17 Comment(3)
Could this be configured for Kotlin?Entreat
Configuration with name 'testCompile ' not found.Decillion
@Decillion Configurations for compiling got new names starting from Gradle 7.x, testImplementation would be the replacement for testCompile. docs.gradle.org/current/userguide/…Dewyeyed
C
17

Unlike the accepted answer it's better to use the following:

allprojects {
  plugins.withType(JavaPlugin) {
    dependencies {
      testCompile 'junit:junit:4.12'
    }
  }
}

The changes will be applied immediately if java plugin already exists or will watch for it to be added and apply later.

Updated

At the moment I use better way to control configuration for plugin - pluginManager. The effect is the same as for plugins.withType, but you don't have to know plugin's class name:

Example for org.springframework.boot plugin:

apply plugin: 'org.springframework.boot'

allprojects {
  pluginManager.withPlugin('org.springframework.boot') {
    springBoot {
      buildInfo()
      layout 'DIR'
    }
  }
}
Caesarea answered 30/1, 2017 at 6:14 Comment(1)
Thank you for that variant. For me, there is no difference in them, for all my subprojects are java ones and I don't use any conditional.Accept
I
6

root/build.gradle

allprojects {
    if (plugins.hasPlugin('java')) {
        dependencies {
            testCompile 'junit:junit:4.12'
        }
    }
}
Inflexed answered 26/1, 2017 at 14:17 Comment(3)
Could this be configured for Kotlin?Entreat
Configuration with name 'testCompile ' not found.Decillion
@Decillion Configurations for compiling got new names starting from Gradle 7.x, testImplementation would be the replacement for testCompile. docs.gradle.org/current/userguide/…Dewyeyed

© 2022 - 2024 — McMap. All rights reserved.