【问题标题】:gradle includes transitive runtime dependency as compile dependencygradle 包含传递运行时依赖项作为编译依赖项
【发布时间】:2016-01-28 16:06:51
【问题描述】:

我在 gradle 依赖管理中遇到了一个奇怪的行为,其中项目 A 将项目 B 引用为编译依赖项,而项目 B 将库 C 引用为运行时依赖项。现在我可以在我的项目 A 中使用库 C 中的类了。

我的问题:(为什么)这是错误还是功能?

可以使用 gradle 2.9 和 2.10 以及以下最小设置重现该问题:

// settings.gradle
include ':A', ':B'
// build.gradle
allprojects {
    apply plugin: 'java'
    apply plugin: 'maven'

    repositories {
        mavenLocal()
        mavenCentral()
    }
}

project(':A') {
    dependencies {
        compile project(':B')
    }
}

project(':B') {
    dependencies {
        runtime "org.slf4j:slf4j-log4j12:1.7.13"
    }
}

如您所见,gradle :A:dependencies 显示

[...]

compile - Compile classpath for source set 'main'.
\--- project :B
     \--- org.slf4j:slf4j-log4j12:1.7.13
          +--- org.slf4j:slf4j-api:1.7.13
          \--- log4j:log4j:1.2.17
[...]

并且在项目 A 中的 java 代码中使用 log4j 是完全可能的。

【问题讨论】:

  • 感谢迈克尔的提问。在这种情况下 gradle 的行为是完全违反直觉的 :-(

标签: java gradle dependency-management


【解决方案1】:

对于 Android 库 (aar) 传递运行时依赖项,从 5.0 开始,Gradle 已修复此问题。

【讨论】:

【解决方案2】:

this问答。如果您不指定配置,Gradle 将选择从 runtime 扩展而来的 default 配置。快速解决方法是使用

compile project(path: ":B", configuration: "compile")

【讨论】:

  • default 配置扩展自runtime,这意味着,根据问答的解释,“它包含runtime 配置的所有依赖项和工件,可能还有更多”。运行时配置中项目“:B”的依赖是runtime。这仍然不能解释为什么依赖项slf4j-api 在项目“:A”中显示为compile
  • compile project(':B') 方法从项目 B 获取 default 配置并将其添加到项目 A 的 compile 配置中。因此,将 B 的 runtime 依赖添加到 A 的 compile 依赖中是合乎逻辑的
  • 我与@dmoebius 离线讨论了这个问题,虽然答案是完全正确且有帮助的,但应牢记以下几点:明确指定compile 配置确实会阻止您的项目编译类路径被传递运行时依赖“污染”,但您的项目 runtime 类路径现在也缺少这些传递运行时依赖。因此,您可以使用defaultconfiguration,或者您必须添加第二个依赖项以将runtime映射到runtimeruntime project(path: ":B", configuration: "runtime")
  • 在这种情况下无需显式指定runtime 配置。由于default 扩展了runtime 你可以只使用compile project(':B')
  • dependencies {} 部分中的每一行都配置了一个配置(即编译或运行时),因此(至少对我而言)您永远不会在一行代码中配置两个配置是合乎逻辑的。我希望 maven 的行为方式相同(例如,所有传递的运行时/编译依赖项都添加到与声明的 相同的范围)
猜你喜欢
  • 1970-01-01
  • 2013-06-29
  • 2015-03-12
  • 2013-04-21
  • 1970-01-01
  • 2020-02-12
  • 2011-09-29
  • 1970-01-01
  • 2018-08-03
相关资源
最近更新 更多