字节流的博客

Gradle 依赖冲突解决

Gradle

在 Java 的项目中,引入过多的第三方 SDK,很容易造成依赖冲突,导致一个组件出现两个或多个版本,从而导致某个 SDK 无法正常使用。

像我使用了阿里云 OSS 的 Java SDK(com.aliyun.oss : aliyun-sdk-oss : 2.2.3),导致我另一个模块的 HTTPS 请求无法发送。应该是 httpclient 包出现了冲突,在 Maven 仓库 查看一下 com.aliyun.oss : aliyun-sdk-oss : 2.2.3 的依赖:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4.1</version>
</dependency>
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>

可知,其依赖于 httpclient 4.4.1 ,而我的一个模块则依赖 于 httpclient 4.5.2,所以产生了冲突。

那怎么解决呢?去掉一个依赖就行。那就去掉 OSS SDK 这个低版本的 httpclient 吧。

可在 build.gradle 中配置如下:

1
2
3
4
compile('com.aliyun.oss:aliyun-sdk-oss:2.2.3') {
transitive = true
exclude group: 'org.apache.httpcomponents', module: 'httpclient'
}

即可排除 com.aliyun.oss:aliyun-sdk-oss:2.2.3httpclient 的依赖,又不影响其他子依赖的引入。

其中 transitive 配置为 true,让 Gradle 自动处理其子依赖;exclude 的配置项为排除的子依赖,不进行引入。

详情请参考 Gradle 官方文档

Thanks! 😊