简介
dependencies用来配置当项目的依赖项。我们常常在gradle配置文件中看到api,implementation,compile……。
dependencies {
testImplementation "org.springframework.boot:spring-boot-starter-test"
compileOnly "org.springframework.boot:spring-boot-configuration-processor"
compile group: 'com.github.xiaoymin', name: 'knife4j-spring-ui', version: '2.0.1'
implementation 'org.springframework.cloud:spring-cloud-starter-config'
api 'com.squareup.okhttp3:okhttp:3.14.7'
}
dependencies类型
ependencies的类型可以分为以下几种
compile
- testCompile
- debugCompile
- releaseCompile
- compileOnly
implementation
- testImplementation
- debugImplementation
- releaseImplementation
provided
api
compile
从依赖上讲,用compile修饰的配置会传递依赖,而大多数的依赖冲突都是由compile产生的,什么是传递依赖?
打个比方:我们现在有libA,然后libB用compile依赖libA,最后libC依赖libB。那这个时候,libC自然能够使用libA的内容,因为libA的内容跟随这个libB而传递到了libC中。
而且compile得越多,所产生的依赖树也就越长,也就越难控制。
从编译上讲,使用compile配置的依赖项,会跟随打包流程将源码打包到jar中。
这两个依赖项配置和compile是差不多的,也会产生传递依赖,唯一不同的是,testcompile和
Testcompile不会参与源码打包,只会参与测试包的打包,并且只有在测试模式下启动才会生效,debug和release包不生效。
debugCompile和releaseCompile
debugCompile
只在buildType为debug的时候参与打包,release不参与打包,比方说我们的内存泄露检测工具-LeakCanary,其实我们也只是需要在debug模式下打包调试,而发布release版本就需要进行打包了,所以用debugCompile来进行配置
releaseCompile
releaseCompile和debugCompile完全相反,只在release模式下参与打包,应用场景不是很多。
implementation
implementation 是Gradle4.1新增的依赖方式,implementation和compile不同,该依赖方式不会产生传递依赖,implementation有点像provided和、debugCompile和releaseCompile的集合体。
来个具体场景,例如:有libA公共库,libB通过implementation依赖libB,然后app无论通过什么方式依赖libB,lib1的依赖都不会传递过来,必须要在app中重新依赖一次。如下图:
使用implementation有什么好处呢?
很大程度减少重复依赖的问题
在开源 lib 的时候尽量采用implementation的方式依赖一些v4、v7包
provided
只参与编译,不参与打包。例如说有libB依赖了libA,moduleC又同时依赖了libA和libB,那么libB就可以使用provided来依赖libA。
api
api是Gradle4.1新增的依赖方式,其作用于compile基本一致。
总结
对于使用Gradle plugin 3.X以上版本的gradle,我们应该转而使用implementation,减少compile的使用,避免依赖冲突的产生。如果我们有开放的lib,那么更加应该使用implementation导入依赖,尽量少给lib的使用者造成困扰。