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

本文深入探讨了Gradle 3.0.0以上版本中引入的api和implementation依赖配置,对比了它们与compile配置的区别。通过示例展示了如何使用这些配置来避免内部库的不当暴露,从而提高构建效率和代码安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值