我是如何解决依赖包冲突的?

1,108 阅读2分钟

版本冲突天天见

最近,和 AS 君的某个红色小错误非常有缘分,经常见面。

从报错信息中,得知是冲突原因是 support-annotations 有两个版本, 26.1.0 和 27.1.1 。

感觉瞬间就找到了问题有没有?

因为 build.gradle 中并没有对 support-annotations 的明显依赖。

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

依赖树溯源

对于以上问题,处理 AS 爆红的多年经验告诉我,需要打印项目的依赖树的时候到了!

./gradlew :app:dependencyInsight --dependency support-annotations --configuration debugAndroidTestCompileClasspath

使用 dependencyInsight 命令支持查看某个库在项目中的版本依赖。报错信息说明冲突发生在 for app 和 for test app ,因此选择打印 debugAndroidTestCompileClasspath 配置下的依赖树。

拿到依赖树,结合项目的 build.gradle ,对比得到造成冲突是这仨库的锅:

  • com.android.support:appcompat-v7:26.1.0 ---> (26.1.0)

  • com.android.support.test:runner:1.0.2 ---> (27.1.1)

  • com.android.support.test.espresso:espresso-core:3.0.2 ---> (27.1.1)

原因找到了,问题就很好解决了,排除掉冲突的其中一个版本即可。因为 support 库一般要保持统一版本,所以我选择排除其他库的冲突版本。

androidTestImplementation ('com.android.support.test:runner:1.0.2'){
      exclude group: 'com.android.support'
  }
  androidTestImplementation ('com.android.support.test.espresso:espresso-core:3.0.2'){
      exclude group: 'com.android.support'
  }

另一个方法

开发工作中,遇到依赖库版本冲突问题,是很常见的问题,通过以上步骤基本都能解决,但是有时候项目很庞大,找起来挺费事。针对这种情况,有一个简单粗暴的方法。

在 project 的 build.gradle 中添加如下的代码。作用是在项目构建时,遍历所有依赖,然后 com.android.support 包下的依赖替换同一个版本。


buildscript {


	  subprojects {
	        project.configurations.all {
	            resolutionStrategy.eachDependency { details ->
	                if (details.requested.group == 'com.android.support'
	                        && !details.requested.name.contains('multidex') ) {
	                    details.useVersion "26.1.0"
	                }
	            }
	        }
	    }
    
}

这个方法,解决的很有效率,但是每次构建的时候,多了一个遍历过程,会加长构建时间。因此,只建议应急用,推荐使用 exclude 关键字排除。


以上就是最近一次解决问题的经验分享,希望对大家有帮助。

小伙伴们如果觉得还不错,或者发现了错误,或者有更好的想法。都请不要害羞,大声说出来,作者热烈欢迎你的点赞和评论呐。

欢迎关注博主的微信公众号,快快加入哦,期待与你一起成长!

欢迎关注博主的微信公众号,快快加入,期待与你一起成长!