Better

业精于勤荒于嬉

Gradle 依赖申明方式

Better's Avatar 2017-12-12 Android

  1. 1. implementation
  2. 2. api
  • 用处
  • 参考
  • 在《Gradle For Android》中写到
    Gradle的依赖就是一系列的文件集合,一些标准的概念:

    • compile
    • apk
    • provided
    • testCompile
    • androidTestCompile

    compile默认的配置,将所依赖的buildeType或Flavor都编译。将添加到cliassPath和生产的apk文件中。
    apk中的依赖只会要添加到最终的apk中,不参与编译。
    providedapk正好相反,不会添加到apk中,只在编译使用。apkprovides两个只能使jar依赖,添加Library将会报错。
    testCompileandroidTestCompile只是用在测试过程中。只会执行在测试相关的任务中。只会被打包到test相关的apk,而不是release相关的apk

    在AS3.0之后引入了新的概念implementationapi,用来替换compile。有点强力推荐的感觉:

    The compile configuration still exists but should not be used as it will not offer the guarantees that the api and implementation configurations provide.

    implementation

    只能在当前模块使用,不能向外暴露出去。
    这样做的好处是:

    • 依赖关系不会泄漏到消费者的编译类路径中,所以永远不会意外地依赖于传递依赖项
    • 由于减少的类路径大小编译更快
    • 当实现依赖关系发生变化时,重新编译会更少:消费者不需要重新编译
    • cleaner发布:当与新的maven-publish插件结合使用时,Java库会生成POM文件,这些文件可以精确地区分编译库所需的内容和运行时使用库所需的内容(换句话说,不要混合编译library本身所需的东西,以及编译library所需的东西)。

    api

    当前的模块可以用,并且可以向外暴露给其他模块使用。跟以前的compile功能一样。

    用处

    引用Library的时候会遇到,某个库版(比如glide)版本不匹配。解决方式是不使用Library的库A

    1
    2
    3
    compile(project(':Library
    exclude group: 'com.github.bumptech.glide', module: 'glide'
    }

    现在可将Library的Glide依赖改为implementation就可以了。

    想外部使用就是api,不想让外部使用就是implememation

    参考

    java_library_separation
    Gradle配置implementation、api与compile的区别
    Implementation Vs Api in Android Gradle plugin 3.0

    This article was last updated on days ago, and the information described in the article may have changed.