Gradle依赖配置 api、implementation、compile区别

Gradle3.0.0以上版本引入了新的依赖配置,新增了apiimplement来代替compile依赖配置。其中 api 和以前的 compile 依赖配置是一样的。使用 implementation 依赖配置,会显著提升构建时间。

假如我们一个名 MyLibrary 的 module 类库和一个名为 InternalLibrary 的 module 类库。里面的代码类似这样:

//internal library module
public class InternalLibrary {
    public static String giveMeAString(){
        return "hello";
    }
}

//my library module
public class MyLibrary {
    public String myString(){
        return InternalLibrary.giveMeAString();
    }
}

MyLibrary 中 build.gradle 对 InternalLibrary 的依赖如下:

dependencies {
    api project(':InternalLibrary')
}

然后在主 module 的 build.gradle 添加对 MyLibrary 的依赖:

dependencies {
    api project(':MyLibrary')
}

在主 module 中,使用 api 依赖配置 MyLibrary 和 InternalLibrary 都可以访问:

//so you can access the library (as it should)
MyLibrary myLib = new MyLibrary();
System.out.println(myLib.myString());

//but you can access the internal library too (and you shouldn't)
System.out.println(InternalLibrary.giveMeAString());

使用这种方法,会泄露一些不应该被使用的实现。

为了阻止这种情况,Gradle 新增了 implementation 配置。如果我们在 MyLibrary 中使用 implementation 配置:

dependencies {
    implementation project(':InternalLibrary')
}

使用这个 implementation 依赖配置在应用中无法调用 InternalLibrary.giveMeAString()。如果 MyLibrary 使用 api 依赖 InternalLibrary,无论主 module 使用 api 还是 implementation 依赖配置,主 module 中都可以访问 InternalLibrary.giveMeAString()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
gradle implementationcompile都是在项目中使用的依赖管理关键字。 在旧版本的Gradle中,使用的是compile关键字来引入项目中所需要的依赖库。例如,使用compile 'com.android.support:appcompat-v7:28.0.0'来引入Android Support库中的appcompat库。 然而,在Gradle 3.0及以上的版本中,compile已经被implementation所取代。这是由于implementation可以更好地处理依赖的传递性问题。所谓的传递性问题是指当一个库依赖另外一个库时,是否需要将被依赖的库也自动地引入到项目中。 通过使用implementation关键字,Gradle能够更好地优化编译过程,只将直接使用的库引入项目中,而不会将间接使用的库也引入项目中。这可以有效减少项目的编译时间,并减少最终应用包的大小。 例如,假设库A依赖库B,而项目只直接使用了库A。如果使用compile关键字,则会将库B也引入到项目中,即使项目中并没有直接使用库B。但如果使用implementation关键字,则只会将库A引入项目中,不会引入库B,从而减少了项目的依赖。 除了implementation之外,还有另外两个依赖管理关键字:api和testImplementationapi关键字可以将依赖库引入到项目的编译路径中,并可以传递给依赖项目。而testImplementation关键字则是专门用于引入测试时所需的库。 总而言之,compile和implementation都是用于项目中的依赖管理,但Gradle 3.0及以上的版本推荐使用implementation来更好地管理项目的依赖关系。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值