Android Gradle dependencies 方式:classpath、implementation、api 的區(qū)別

  1. classpath:一般是添加 buildscript 本身需要運(yùn)行的東西,buildScript是用來加載gradle腳本自身需要使用的資源,可以聲明的資源包括依賴項(xiàng)、第三方插件、maven倉庫地址等。
    某種意義上來說,classpath 聲明的依賴,不會編譯到最終的 apk 里面。
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        //butterknife注入
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.2.1'
    }
}
  1. implementation、api :在模塊中的build.gradle中,給 dependencies 中添加的使應(yīng)用程序所需要的依賴包,也就是項(xiàng)目運(yùn)行所需要的東西。
    • implementation:對于使用了該命令編譯的依賴,對該項(xiàng)目有依賴的項(xiàng)目將無法訪問到使用該命令編譯的依賴中的任何程序,也就是將該依賴隱藏在內(nèi)部,而不對外部公開。
    • api:對比 implementation,不會隱藏。(等同于 Android Gradle 2.x 版本的 compile(已deprecated))

如果 lib C 依賴了lib A 2.0版本,lib B implementation依賴了lib A 1.0版本:
那么編譯期,libC 可訪問2.0版本的libA ,libB可訪問1.0版本的libA。但最終打到apk中的是2.0版本(通過依賴樹可看到)。
在運(yùn)行期,lib B 和lib C都可訪問lib A的2.0版本(因?yàn)閍pk的所有dex都會放到classLoader的dexPathList中)。

android {...}
...
dependencies {
    // The 'compile' configuration tells Gradle to add the dependency to the
    // compilation classpath and include it in the final package.

    // Dependency on the "mylibrary" module from this project
    api project(":mylibrary")

    // Remote binary dependency
    implementation 'com.android.support:appcompat-v7:27.1.1'

    // Local binary dependency
    api fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.jakewharton:butterknife:8.2.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.2.1'
}

更多信息參考:

https://developer.android.com/studio/build/
https://developer.android.com/studio/build/build-variants#dependencies
https://docs.gradle.org/current/userguide/dependency_management_for_java_projects.html
https://docs.gradle.org/current/userguide/introduction_dependency_management.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容