此答案将展示项目中implementation、api 和compile 之间的区别。
假设我有一个包含三个 Gradle 模块的项目:
- app(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')
}
你认为myandroidlibrary build.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配置的一个要点,更详细的解释请参考Table 49.1. Java Library plugin - configurations used to declare dependencies。
https://github.com/aldoKelvianto/ImplementationVsCompile 上提供了此答案的示例项目