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

9次阅读

共计 1671 个字符,预计需要花费 5 分钟才能阅读完成。

将在一个项目中展示 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()); // 无法编译的

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

如果要 公开依赖项,请使用 apicompile

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

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

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

正文完
 0