How to read subproject ext property value from root project?

I have a subproject Gradle like

project.ext.foo = "bar"
...

And I have the root project Gradle file as

subprojects {
    if (project.hasProperty("foo")) {
        // not true
    }

    def hasFoo = project.findProperty('foo') ?: ""
    // not finding it

}

I need to configure the subprojects in the root gradle file based on a project set or not set in the individual subproject.

Dumping project.properties.each {} doesn’t seem to help.

Any help is appreciated.

You’re most likely running into an order of operations problem. If you add some debug prints you’ll probably see that the subprojects block is executed before the subprojects are configured.

println "configuring subproject $name"
project.ext.foo = "bar"
subprojects {
    println "config $name from root"
    ...
}

Are you sure you need to do this? If you are just trying to extract common configuration logic then you can do this in a variety of alternative ways. In general, cross-project configuration is frowned upon, it makes builds difficult to read and comprehend.

Here’s one very simply solution:
common.gradle

// common build logic
if (project.hasProperty("foo")) {
    println "has foo"
}

Then in each subproject’s build.gradle:

project.ext.foo = "bar"
...

apply from: rootProject.file("common.gradle")

This way, when a user reads the subproject’s build script, all of the applicable logic is visible and not hidden in the root project.

1 Like