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

猜你喜欢

转载自blog.csdn.net/weixin_43499030/article/details/90049494