在更新到Android Studio 3.0并创建一个新项目之后,我注意到在 build.gradle
中有一种新方法来添加新的依赖项而不是 compile
有 implementation
而不是 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'
它们之间有什么区别,我应该使用什么?
5 回答
The brief difference in layman's term is:
如果您正在使用通过公开所述依赖项的成员来为其他模块提供支持的接口或模块,那么您应该使用'api' .
如果要创建要在内部实现或使用所述依赖项的应用程序或模块,请使用'implementation' .
'compile'与'api'的工作方式相同,但是,如果您只是实现或使用任何库,'implementation'将更好地工作并节省您的资源 .
阅读@aldok的答案以获得一个全面的例子 .
Brief Solution:
更好的方法是用
implementation
依赖项替换所有compile
依赖项 . 只有泄漏模块接口的地方,才应使用api
. 这应该会导致更少的重新编译 .Explain More:
Before Android Gradle plugin 3.0 :我们遇到了一个很大的问题,即一个代码更改导致所有模块被重新编译 . 造成这种情况的根本原因是Gradle不知道您是否通过另一个模块泄漏模块的接口 .
After Android Gradle plugin 3.0 :最新的Android Gradle插件现在要求您明确定义是否泄漏模块的界面 . 基于此,它可以在应该重新编译的内容上做出正确的选择 .
因此,
compile
依赖项已被弃用,取而代之的是两个新的依赖项:api
:您通过自己的界面泄漏了此模块的接口,这意味着与旧的compile
依赖项完全相同implementation
:您只在内部使用此模块,不会通过您的界面泄漏它因此,如果已使用模块的接口发生变化,您现在可以明确告诉Gradle重新编译模块 .
礼貌Jeroen Mols博客
Compile
配置已弃用,应替换为implementation
或api
.您可以在https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation阅读文档 .
简介部分是 -
有关进一步说明,请参阅此图像 .
这个答案将展示项目中
implementation
,api
和compile
之间的区别 . 假设我有一个包含三个Gradle模块的项目:app(Android应用程序)
myandroidlibrary(Android库)
myjavalibrary(一个Java库)
app
有myandroidlibrary
作为依赖项 .myandroidlibrary
有myjavalibrary
作为依赖项 .myjavalibrary
有一个MySecret
类myandroidlibrary
有MyAndroidComponent
类操纵MySecret
类的值 .最后,
app
只对myandroidlibrary
的值感兴趣现在,让我们谈谈
app
build.gradle的依赖关系 . 它非常简单直观 .您认为
myandroidlibrary
build.gradle会是什么样子?我们有三种选择:Compile and Api
如果你正在使用
compile
和api
. 我们的Android应用程序现在能够访问myandroidcomponent
依赖项,这是一个MySecret
类 .Implementation
如果您正在使用
implementation
配置,则不会公开MySecret
.那么,您应该选择哪种配置?这真的取决于你的要求 .
如果要公开依赖项,请使用
api
或compile
,如果您不想公开依赖项(隐藏内部模块),请使用implementation
.这只是Gradle配置的要点,有关详细说明,请参阅Table 49.1. Java Library plugin - configurations used to declare dependencies .
有关此答案的示例项目,请访问https://github.com/aldoKelvianto/ImplementationVsCompile
tl;dr
只需更换:
compile
与implementation
testCompile
与testImplementation
debugCompile
与debugImplementation
androidTestCompile
与androidTestImplementation
compileOnly
仍然有效 . 它在3.0中添加以替换提供而不是编译 . (_367872_在Gradle没有't have a configuration name for that use-case and named it after Maven'提供范围时介绍 . )这是Gradle 3.0即将发生的重大变化之一Google announced at IO17 .
compile
配置为now deprecated,应替换为implementation
或api
来自Gradle documentation:
Note: 如果您只在应用程序模块中使用库 - 常见情况 - 您将不会注意到任何差异 .
如果您有一个复杂的项目,模块相互依赖,或者您正在创建一个库,那么您将只能看到差异 .