When Gradle executes a Script, it compiles the Script into a class that implements the Script interface, which means that all properties and methods declared by the Script interface are available in the Script.

In Gradle’s Domain model, all enhanced objects allow the user to define additional properties, such as projects, tasks, source sets, etc. Additional properties can be added, read, and set via the ext property of the owning object. It is also possible to add multiple attributes simultaneously using ext blocks.

Here’s an example:

apply plugin: "java"
ext {
    springVersion = "3.1.0. RELEASE"
    emailNotification = "[email protected]"
}
sourceSets.all { ext.purpose = null }
sourceSets {
    main {
        purpose = "production"
    }
    test {
        purpose = "test"
    }
    plugin {
        purpose = "production"
    }
}
task printProperties << {
    println springVersion
    println emailNotification
    sourceSets.matching { it.purpose == "production" }.each { println it.name }
}   
Copy the code

Line by line analysis:

Add two extension properties to the Project object via ext code blocks.

Add the Purpose extension attribute to all sourceSets objects.

Assign the Purpose attribute to the sourceSets objects named main,test, and Plugin, respectively.

Finally, gradle printProperties prints:

Groovy automatically converts a reference to a property into a call to the appropriate getter or setter method:

    println project.buildDir
    println getProject().getBuildDir()
Copy the code

Output:

For more of Jerry’s original articles, please follow the public account “Wang Zixi “: