這個答案將展示在一個項目implementation
,api
和compile
之間的差異。比方說,我有三個搖籃模塊項目:
- 應用(Android應用程序)
- myandroidlibrary(一個Android庫)
- myjavalibrary(一個Java庫)
app
有myandroidlibrary
作爲依賴關係。 myandroidlibrary
具有myjavalibrary
作爲依賴關係。
應用 - > 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
的build.gradle。它非常簡單直觀。
dependencies {
implementation project(':myandroidlibrary')
}
你覺得myandroidlibrary
的build.gradle應該樣子?我們有三個選擇:
dependencies {
// Option #1
implementation project(':myjavalibrary')
// Option #2
compile project(':myjavalibrary')
// Option #3
api project(':myjavalibrary')
}
什麼是它們之間的區別,什麼我應該使用?
編譯和API
如果您使用compile
和api
。我們的Android應用程序現在能夠訪問myandroidcomponent
依賴項,這是一個MySecret
類。
TextView textView = findViewById(R.id.text_view);
textView.setText(MyAndroidComponent.getComponent());
// You can access MySecret
textView.setText(MySecret.getSecret());
實施
如果您使用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對此有更詳細的解釋。
快樂探索
誰是「消費者」? – Suragch
消費者是使用庫的模塊。在Android的情況下,它是Android應用程序。我認爲這很清楚,我不確定這是否是你要求的。 – humazed
這也是我聽起來的樣子。但是,如果我正在創建一個庫,當然我希望它的API能夠暴露給應用程序。否則,應用程序開發人員將如何使用我的庫?這就是爲什麼我沒有獲得隱藏依賴項的「實現」的含義。我的問題有意義嗎? – Suragch