这个答案将展示之间的差异implementation,api以及compile在一个项目。
假设我有一个包含三个Gradle模块的项目:
- 应用(Android应用)
- myandroidlibrary(Android库)
- myjavalibrary(Java库)
app具有myandroidlibrary与依赖。myandroidlibrary具有myjavalibrary 与依赖。

myjavalibrary有MySecret课
public class MySecret {
public static String getSecret() {
return "Money";
}
}
myandroidlibrary拥有MyAndroidComponent操纵MySecret阶级价值的阶级。
public class MyAndroidComponent {
private static String component = MySecret.getSecret();
public static String getComponent() {
return "My component: " + component;
}
}
最后,app只对来自myandroidlibrary
TextView tvHelloWorld = findViewById(R.id.tv_hello_world);
tvHelloWorld.setText(MyAndroidComponent.getComponent());
现在,让我们谈谈依赖性...
app需要消耗:myandroidlibrary,所以在appbuild.gradle中使用implementation。
(注意:您也可以使用api / compile。但是请稍等片刻。)
dependencies {
implementation project(':myandroidlibrary')
}

您认为myandroidlibrarybuild.gradle应该是什么样?我们应该使用哪个范围?
我们有三种选择:
dependencies {
// Option #1
implementation project(':myjavalibrary')
// Option #2
compile project(':myjavalibrary')
// Option #3
api project(':myjavalibrary')
}

它们之间有什么区别,我应该使用什么?
编译或Api(选项#2或#3)

如果您使用compile或api。我们的Android应用程序现在可以访问myandroidcomponent依赖项,它是一个MySecret类。
TextView textView = findViewById(R.id.text_view);
textView.setText(MyAndroidComponent.getComponent());
// You can access MySecret
textView.setText(MySecret.getSecret());
实施(选项1)

如果您使用的是implementation配置,MySecret则不会公开。
TextView textView = findViewById(R.id.text_view);
textView.setText(MyAndroidComponent.getComponent());
// You can NOT access MySecret
textView.setText(MySecret.getSecret()); // Won't even compile
那么,您应该选择哪种配置?那真的取决于您的要求。
如果要公开依赖项,请使用api或compile。
如果您不想公开依赖项(隐藏您的内部模块),请使用implementation。
注意:
这只是Gradle配置的要点,请参阅表49.1。Java库插件-用于声明依赖关系的配置,以进行更详细的说明。
可在https://github.com/aldoKelvianto/ImplementationVsCompile上找到此答案的示例项目。