【问题标题】:Don't use later library version from transitive dependency in Gradle不要在 Gradle 中使用来自传递依赖的更高版本的库
【发布时间】:2015-10-02 20:14:48
【问题描述】:

在我的 Android 项目中我使用

compile 'com.squareup.okhttp:okhttp:2.2.0'

我需要 2.2.0 版中的 okhttp 才能使我的代码正常工作。但是我添加的时候有问题

compile('io.intercom.android:intercom-sdk:1.1.2@aar') {
        transitive = true
}

因为在 intercom-sdk 内部又存在 okhttp 依赖,供后续版本使用:

compile 'com.squareup.okhttp:okhttp:2.4.0'

我的代码使用了我想要的更高版本 2.4.0 而不是 2.2.0 的结果。请问有什么方法可以在我的模块中使用我指定的 2.2.0 并让对讲机使用它的 2.4.0?

【问题讨论】:

    标签: gradle dependencies build.gradle transitive-dependency


    【解决方案1】:

    你可以这样使用:

    compile('io.intercom.android:intercom-sdk:1.1.2@aar') {
        exclude group: 'com.squareup.okhttp', module: 'okhttp'
      }
    

    不过要注意。如果库使用 2.2.0 版本中不存在的方法,它将失败。

    【讨论】:

    • 谢谢。这就是我担心的,因为我已经尝试过了,正如你所说,它失败了。你能解释一下如果我删除传递会发生什么吗?
    • 据我所知,当你添加@aar注解时,要使依赖传递(即依赖的依赖),你应该添加“transitive=true”。
    • 标记现在您需要使用组 ID:com.squareup.okhttp3
    【解决方案2】:

    您应该定义解决策略来设置特定版本。这将保证无论传递依赖版本是什么,您都将获得所需的正确版本:

    allProjects {
       configurations.all {
           resolutionStrategy {
               eachDependency { DependencyResolveDetails details ->
                   if (details.requested.name == 'okhttp') {
                       details.useTarget('com.squareup.okhttp:okhttp:2.2.0')
                   }
                }
            }
         }
      }
    

    在较新版本的 Gradle 中,您可以使用:

    allProjects {
       configurations.all {
           resolutionStrategy.force 'com.squareup.okhttp:okhttp:2.2.0'
         }
     }
    

    【讨论】:

    • 谢谢。但这不会迫使我的对讲机依赖也使用 2.2.0 吗?还是对讲继续使用2.4.0?
    • 在依赖配置中只能有一个版本的 jar。如果您想要两个或更多版本,则需要将它们放在单独的依赖项中,并为您的输出组合依赖项。您还需要确保在运行时将不同的库加载到唯一的类加载中。
    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 2016-11-30
    • 2019-04-07
    • 2021-01-24
    • 2017-12-26
    • 2020-04-12
    • 2011-12-22
    • 2018-04-23
    相关资源
    最近更新 更多