不会自动为来自 Android Gradle 插件 8.0 的 Maven 发布创建软件组件

Software Components will not be created automatically for Maven publishing from Android Gradle Plugin 8.0

使用 Gradle 7.2 和这些插件:

plugins {
    id 'com.android.library' // Android Gradle Plugin 7.1.2
    id 'maven-publish'
}

它仍然有效,但给了我这个弃用警告:

WARNING: Software Components will not be created automatically for Maven publishing from Android Gradle Plugin 8.0. To opt-in to the future behavior, set the Gradle property android.disableAutomaticComponentCreation=true in the gradle.properties file or use the new publishing DSL.

release notes也提到了,但这些参考了过时的文档:

Starting AGP 8.0, automatic component creation will be disabled by default. Currently, AGP 7.1 automatically creates a component for each build variant, which has the same name as the build variant, and an an all component that contains all the build variants. This automatic component creation will be disabled. To transition to the new behavior, you should manually disable automatic component creation by setting android.disableAutomaticComponentCreation to true.
For more information, see Use the Maven Publish plugin.


但是在文件 gradle.properties 中为 AGP 8.0 默认行为启用预览时:

android.disableAutomaticComponentCreation=true

找不到属性 components.release:

FAILURE: Build failed with an exception.

* Where:
Script 'publish.gradle' line: 53

* What went wrong:
A problem occurred configuring project ':library'.
> Could not get unknown property 'release' for SoftwareComponentInternal set of type org.gradle.api.internal.component.DefaultSoftwareComponentContainer.

offending line 内容为:

release(MavenPublication) {
    from components.release
}

变体仍然存在,但它不再创建组件:

androidComponents {
    onVariants(selector().all(), {
        println "$it.name"
    })
}

如何升级到这个“新的发布 DSL”并创建一个软件 component 来发布?

根据PublishingOptions,必须定义一个android.publishing块:

android {
    publishing {
        singleVariant('release') {
            withSourcesJar()
            withJavadocJar()
        }
        // ...
    }
}

一次定义多个变体:

android {
    publishing {
        multipleVariants {
            withSourcesJar()
            withJavadocJar()
            allVariants()
        }
    }
}

然后例如。 components.getByName('release')又会知道

Android Studio 团队刚刚在 https://developer.android.com/studio/publish-library/configure-pub-variants

发布了一些有用的用户文档