Gradle 依赖关系中 compile和 implementation的区别

将在一个项目中展现implementation,api以及compile之间的差别。html

假设我有一个包含三个Gradle模块的项目:java

  • app(Android应用)
  • my-android-library(Android库)
  • my-java-library(Java库)

app具备my-android-library与依赖。my-android-library具备my-java-library依赖。android

依赖1

my-java-library有一个MySecret班git

public class MySecret {

    public static String getSecret() {
        return "Money";
    }
}

my-android-library 拥有一个类 MyAndroidComponent,里面有调用 MySecret 类的值。github

public class MyAndroidComponent {

    private static String component = MySecret.getSecret();

    public static String getComponent() {
        return "My component: " + component;
    }    
}

最后,app 只对来自 my-android-libraryapi

TextView tvHelloWorld = findViewById(R.id.tv_hello_world);
tvHelloWorld.setText(MyAndroidComponent.getComponent());

如今,让咱们谈谈依赖性...app

app须要:my-android-library库,因此在app build.gradle文件中使用implementationide

(注意:您也能够使用api/compile, 可是请稍等片刻。)gradle

dependencies {
    implementation project(':my-android-library')      
}

依赖2

您认为 my-android-library 的 build.gradle应该是什么样?咱们应该使用哪一个范围?ui

咱们有三种选择:

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()); // 没法编译的

那么,您应该选择哪一种配置?取决于您的要求。

若是要公开依赖项,请使用 apicompile

若是您不想公开依赖项(隐藏您的内部模块),请使用implementation

注意:
这只是 Gradle 配置的要点,请参阅 表49.1 Java库插件-用于声明依赖的配置,有更详细的说明。

可在https://github.com/aldoKelvia... 上找到此答案的示例项目。

相关文章
相关标签/搜索