Sunday, December 8, 2013

Global properties in gradle

When we have multiple projects and we may want to refer global properties such as dependencies by all sub-projects.

For example we have a project structure like this

So we have a root project called ProjectX and two sub projects called ProjectA and ProjectB. Each of them has their own build.gradle file for gradle build. By default, they all should be named as build.gradle. To distinguish them, we denote them as

  • build.gradleX
  • build.gradleA
  • build.gradleB

Say we want to use the same version of JUnit in all projects, so we need to use the same JUnit dependency and reference the same dependency across all projects.

In build.gradleX, we define a property
ext {
    lib = [
        junit: 'junit:junit:4.11'

In build.gradleA and build.gradleB we refer the dependency by
dependencies {
     compile lib.junit  //This references the property defined in build.gradleX

The mechanism of the above code is, the build.gradleX defines a property in root project(ProjectX) so in its subjects, lib.junit will be read inherited from the root project. But if we define ext.lib in PojectA as well like below then the lib.junit will use its local value. This is good if we want to override the value but if we don't know what happens behind the scene, mistake occurs.
in build.gradleA
ext {
    lib = [
        junit: 'junit:junit:3.0.0'

So, to refer the lib.ext we use
rootProject.lib.junit    //referencing the absolute root project 
parent.lib.junit         //referencing relative parent project which is the root here

No comments:

Post a Comment