Apply maven publish for all subprojects from root project

Sorry if this often repeated question but I could not find answer to my question. I have an Android project with certain number of library modules (subprojects). I need to publish the library from each one of those modules. Instead of duplicating the publishing code in subproject/module gradle file I want to place this code in root project file like:

subprojects {
    plugins.apply("maven-publish") // <-- GETTING ERROR HERE

    configure<PublishingExtension> {
        publications {
            create<MavenPublication>("aar") {
                from(components["release"])
                groupId = "com.example"
                version = "1.0.0"
                artifactId = project.name // Default to project name, can be overridden
            }
        }
        repositories {
            mavenLocal()
        }
    }
}

However, I get this error from the line marked above. I am using gradle version 8.3.

Failed to apply plugin class ‘org.gradle.api.publish.plugins.PublishingPlugin’.

Cannot run Project.afterEvaluate(Action) when the project is already evaluated.

How can I get this addressed and have publishing from common (root) gradle file?

Besides that you should not use plugins. (look at its JavaDoc), the main point is, that you shouldn’t do such cross-project configuration.
It is highly discouraged bad practice and works against some more sophisticated features and optimizations in Gradle.

If you want to centralize build logic, better consider using convention plugins, for example in buildSrc or an included build like gradle/build-logic, for example implemented as precompiled script plugin.

Besides that, it is pointless to add mavenLocal() as publishing repository. While you should avoid using mavenLocal() in general as it is broken by desing in Maven already, it is always implicitly present for publishing anyways, so you do not need to configure it manually.

Great advice. Will followup on your suggestions.

1 Like