边实验边分析 - Gradle如何处理多个库依赖了不同版本的库之间的冲突
比如我们有两个库,一个是dialog-lib
它依赖于okhttp 4.9.0的版本
另一个vox-sdk
版本为3.10.0的okhttp
如果我们把这两个库都引入同一个项目中,会发生什么呢?
在gradle中添加
dependencies {
...
implementation 'io.github.xiaozeiqwe8:vox-sdk:0.9.4'
implementation 'io.github.xiaozeiqwe8:dialog-lib:0.9.8'
}
我们执行一下gradle同步,在External Librarys里查看下载下来的库,发现
其使用的是高版本的okhttp
我们可以在Gradle的官网中查看到相关说明:
Gradle will consider all requested versions, wherever they appear in the dependency graph. Out of these versions, it will select the highest one.
所以Gradle会帮我们进行版本冲突,而其规则就是使用高版本的,这一点和maven不同,相关说明可以在Gradle官网查看到,地址:https://docs.gradle.org/current/userguide/userguide_single.html#sec:version-conflict
扩展:我们可以通过在项目根目录下执行gradlew -q app:dependencies,来查看依赖树的详细信息
从上图中可以看出来,Gradle帮我们选择了4.9.0的版本的okhttp
那么现在问题是我能不能指定使用3.10.0的okhttp呢?也是可以的
修改gradle
dependencies {
...
implementation 'io.github.xiaozeiqwe8:vox-sdk:0.9.4'
implementation('io.github.xiaozeiqwe8:dialog-lib:0.9.8'){
exclude group: 'com.squareup.okhttp3'
}
}
这样,通过增加exclude group,把dialog-lib中的okhttp3的库排除掉,这样,Gradle就会检测到sdk中的3.10.0版本的okhttp3来使用了。