將在一個項目中展示implementation,api以及compile之間的差異。
假設我有一個包含三個Gradle模塊的項目:
- app(Android應用)
- my-android-library(Android庫)
- my-java-library(Java庫)
app具有my-android-library與依賴。my-android-library具有my-java-library依賴。
依賴1
my-java-library有一個MySecret班
public class MySecret { public static String getSecret() { return "Money"; } }
my-android-library 擁有一個類 MyAndroidComponent,里面有調用 MySecret 類的值。
public class MyAndroidComponent { private static String component = MySecret.getSecret(); public static String getComponent() { return "My component: " + component; } }
最后,app 只對來自 my-android-library
TextView tvHelloWorld = findViewById(R.id.tv_hello_world); tvHelloWorld.setText(MyAndroidComponent.getComponent());
現在,讓我們談談依賴性...
app需要:my-android-library庫,所以在app build.gradle
文件中使用implementation
。
(注意:您也可以使用api/compile, 但是請稍等片刻。)
dependencies { implementation project(':my-android-library') }
依賴2
您認為 my-android-library 的 build.gradle
應該是什么樣?我們應該使用哪個范圍?
我們有三種選擇:
dependencies { // 選擇 #1 implementation project(':my-java-library') // 選擇 #2 compile project(':my-java-library') // 選擇 #3 api project(':my-java-library') }
依賴3
它們之間有什么區別,我應該使用什么?
compile 或 api(選項#2或#3)
依賴4
如果您使用 compile 或 api。我們的 Android 應用程序現在可以訪問 MyAndroidComponent 依賴項,它是一個MySecret 類。
TextView textView = findViewById(R.id.text_view); textView.setText(MyAndroidComponent.getComponent()); // 你可以訪問 MySecret textView.setText(MySecret.getSecret());
implementation(選項1)
依賴5
如果您使用的是 implementation 配置,MySecret 則不會公開。
TextView textView = findViewById(R.id.text_view); textView.setText(MyAndroidComponent.getComponent()); // 你無法訪問 MySecret 類 textView.setText(MySecret.getSecret()); // 無法編譯的
那么,您應該選擇哪種配置?取決於您的要求。
如果要公開依賴項,請使用 api 或 compile。
如果您不想公開依賴項(隱藏您的內部模塊),請使用implementation。