Gradle:在“subprojects”块中使用中央依赖声明。

huangapple go评论56阅读模式
英文:

Gradle: Use central declaration of dependencies in "subprojects" block

问题

我按照Gradle的说明来定义依赖关系的中心点。我使用libs.version.toml文件来实现这一点。请参见:链接

举例来说,假设我有这个libs.versions.toml文件:

[versions]
mockito = "4.1.0"
[libraries]
mockito = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito" }

现在,在根或子项目的build.gradle中使用它是可以的,但在定义subprojects块时,用于定义所有子模块的依赖项和插件时,它不起作用。以下是根build.gradle的示例:

plugins {
    (...)
}

// 仅为此模块添加依赖关系
dependencies {
    testImplementation(libs.mockito) // 正常工作
}

subprojects {
    // 为每个子模块添加依赖项
    dependencies {
        testImplementation(libs.mockito) // 不起作用
    }
}

是否有一种方法可以实现这一点,而不必将每个依赖项添加到每个子项目的build.gradle中?我使用的是Gradle 8.0.1。

英文:

I followed Gradle's instructions to a central point to define dependencies. I am using the libs.version.toml file to do that. see: Link

For this example, let's assume, that i have this libs.versions.toml:

[versions]
mockito = "4.1.0"
[libraries]
mockito = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito" }

Now using it in the root or subprojects' build.gradle works fine, but when defining the subprojects block, where I define dependencies and plugins for all submodules, it does not work. Example root build.gradle:

plugins {
    (...)
}

// add dependencies for this module only
dependencies {
    testImplementation(libs.mockito) // works
}

subprojects {
    // add dependencies to every submodule
    dependencies {
        testImplementation(libs.mockito) // doesn't work
    }
}

Is there a way to achieve this, without adding every dependency to each subprojects' build.gradle? I am using Gradle 8.0.1.

答案1

得分: 2

这是Gradle中subprojectallproject块实现方式的一个后果。

你可以通过在libs访问前加上rootProject前缀来使其工作:

subprojects {
    // 向每个子模块添加依赖
    dependencies {
        testImplementation(rootProject.libs.mockito) // 现在有效
    }
}

你可以在Gradle问题跟踪器中找到更多相关信息。

然而,Gradle建议使用约定插件替代allproject / subproject构造。

英文:

This is a consequence of the way the subproject and allproject blocks are implemented in Gradle.

You can make it work by prefixing the libs access with rootProject:

subprojects {
    // add dependencies to every submodule
    dependencies {
        testImplementation(rootProject.libs.mockito) // Now works
    }
}

You can find more information about this in the Gradle issue tracker.

However, Grade recommends to replace usage of allproject / subproject constructs with convention plugins.

huangapple
  • 本文由 发表于 2023年2月23日 23:56:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75547262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定