gradle - Gradle 中的实现、api 和编译之间有什么区别?

标签 gradle build.gradle dependency-management gradle-plugin transitive-dependency

更新到 Android Studio 3.0 并创建新项目后,我注意到在 build.gradle 中有一种添加新依赖项的新方法,而不是 compileimplementation,而不是 testCompile,而是 testImplementation

示例:

 implementation 'com.android.support:appcompat-v7:25.0.0'
 testImplementation 'junit:junit:4.12'

而不是

 compile 'com.android.support:appcompat-v7:25.0.0'
 testCompile 'junit:junit:4.12'

它们之间有什么区别,我应该使用什么?

最佳答案

tl;博士

只需替换:

  • compile 使用 implementation(如果您不需要传递性)或 api(如果您需要传递性)
  • testCompiletestImplementation
  • debugCompiledebugImplementation
  • androidTestCompileandroidTestImplementation
  • compileOnly 仍然有效。它是在 3.0 中添加的,用于替换提供的但不编译。 (当 Gradle 没有该用例的配置名称并以 Maven 提供的范围命名时,引入了 provided。)

这是 Android Gradle plugin 3.0 带来的重大变化之一那个谷歌announced at IO17 .

编译配置为now deprecated并应替换为 implementationapi

来自Gradle documentation :

dependencies {
    api("commons-httpclient:commons-httpclient:3.1")
    implementation("org.apache.commons:commons-lang3:3.5")
}

Dependencies appearing in the api configurations will be transitively exposed to consumers of the library, and as such will appear on the compile classpath of consumers.

Dependencies found in the implementation configuration will, on the other hand, not be exposed to consumers, and therefore not leak into the consumers' compile classpath. This comes with several benefits:

  • dependencies do not leak into the compile classpath of consumers anymore, so you will never accidentally depend on a transitive dependency
  • faster compilation thanks to reduced classpath size
  • less recompilations when implementation dependencies change: consumers would not need to be recompiled
  • cleaner publishing: when used in conjunction with the new maven-publish plugin, Java libraries produce POM files that distinguish exactly between what is required to compile against the library and what is required to use the library at runtime (in other words, don't mix what is needed to compile the library itself and what is needed to compile against the library).

The compile configuration still exists, but should not be used as it will not offer the guarantees that the api and implementation configurations provide.

<小时/>

注意:如果您仅在应用模块中使用库(常见情况),您将不会注意到任何差异。
仅当您有一个模块相互依赖的复杂项目,或者您正在创建一个库时,您才会看到差异。

关于gradle - Gradle 中的实现、api 和编译之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44493378/

相关文章:

eclipse - m2eclipse 不显示工作区项目依赖项,但显示传递依赖项

java - Eclipse maven 仅管理依赖项,仅此而已

gradle - 添加constraintLayout后无法同步项目

android - 在 build.gradle 中找不到参数的方法 uploadArchives()

plugins - Gradle:非法重复错误

gradle - 为 'gradle test' 增加堆内存

java - 任务“:app:compileDebugJavaWithJavac”执行失败

java - Maven 发布更新策略

maven - 我如何告诉 gradle 在 SNAPSHOT 版本上执行 uploadArchives?

java - 处理 AndroidStudio 中的重复条目 : java. util.zip.ZipException