首页 > 解决方案 > Gradle 在多项目中共享属性

问题描述

我对 Gradle 很陌生,正在尝试制作多项目。在根项目中声明所有公共库(以及它们的版本作为属性)并应用插件。

例如,root子项目common
Inrootsettings.gradle类型:

rootProject.name = 'root'
include 'common'

Inrootbuild.gradle类型:

buildscript {
    ext.kotlin_version = '1.3.11'

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

subprojects {
    buildscript {
        repositories {
            mavenCentral()
        }
    }

    apply plugin: 'kotlin'

    repositories {
        mavenCentral()
    }

    dependencies {
        compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    }
}

现在我只想在特定的子项目中使用另一个库。在common's中执行此操作build.gradle

buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version"
    }
}

从 's 文件夹运行 gradle 命令时它工作正常,但从's 文件夹运行时root失败并显示消息。Could not get unknown property 'kotlin_version' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandlercommon

我做错了什么?或者有什么办法吗?在多项目中共享库和属性的最佳实践是什么?

对我来说,它似乎common对它的“父”项目一无所知,所有关系都在 root 的设置中定义。

标签: gradle

解决方案


The reason why Gradle cannot resolve the property is because the project in folder common is named commons. This is caused by a spelling mistake in common's settings.gradle. This is fortunately easy to fix (common/settings.gradle) :

rootProject.name = 'common'

Alternatively, just delete the common/settings.gradle, it's fully optional in this case.

Consider reading the official Gradle documentation for authoring multi-project builds and the guide create multi-project builds for more information and best practices around multi-project builds.


推荐阅读