首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android Gradle dependencies 閉包含義:聲明項目依賴的配置塊

     編輯:程式設計綜合問答

含義

dependencies { } 是 Gradle 構建腳本中**聲明項目依賴**的配置閉包。在其中指定項目編譯、運行、測試所需的外部庫 (AAR/JAR)、模塊依賴、本地文件依賴等。

常見配置

dependencies {
    // 遠程倉庫依賴 (Maven 坐標)
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.google.code.gson:gson:2.8.6'

    // 本地模塊依賴
    implementation project(':mylibrary')

    // 本地 JAR/AAR 文件
    implementation files('libs/custom.jar')
    implementation(name: 'local-aar', ext: 'aar')

    // 測試依賴
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

與 if/for 等語句的關係

  • 無直接語法關係:dependencies 是 Gradle DSL (基於 Groovy/Kotlin) 的特定配置塊,非控制流語句。
  • 可在閉包內使用控制流:因為是 Groovy 代碼,可用 if 條件編譯、for 循環批量添加依賴。
    // 示例:按 flavor 條件依賴
    if (project.hasProperty('flavor') && flavor == 'pro') {
        implementation 'com.pro:feature:1.0'
    }
    
    // 批量添加本地 jars
    fileTree(dir: 'libs', include: '*.jar').each { file ->
        implementation files(file)
    }

關鍵概念

配置用途傳遞性
implementation編譯+打包,不傳遞給消費者否
api編譯+打包+傳遞給消費者是
compileOnly僅編譯期需要,不打包 (如 Lombok)否
runtimeOnly僅運行期需要否
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved