Gradle 內建支援相依性管理

gradle basic 7

相依性管理是一種自動化技術,用於宣告和解析專案所需的外部資源。

Gradle 建置指令碼定義建置專案的程序,這些專案可能需要外部相依性。相依性是指 JAR、外掛程式、函式庫或支援建置專案的原始碼。

版本目錄

版本目錄提供一種方式,可以在 libs.versions.toml 檔案中集中您的相依性宣告。

目錄讓在子專案之間共用相依性和版本設定變得簡單。它也允許團隊在大型專案中強制執行函式庫和外掛程式的版本。

版本目錄通常包含四個區段

  1. [versions] 宣告外掛程式和函式庫會參照的版本號碼。

  2. [libraries] 定義建置檔案中使用的函式庫。

  3. [bundles] 定義一組相依性。

  4. [plugins] 定義外掛程式。

[versions]
androidGradlePlugin = "7.4.1"
mockito = "2.16.0"

[libraries]
googleMaterial = { group = "com.google.android.material", name = "material", version = "1.1.0-alpha05" }
mockitoCore = { module = "org.mockito:mockito-core", version.ref = "mockito" }

[plugins]
androidApplication = { id = "com.android.application", version.ref = "androidGradlePlugin" }

檔案位於 gradle 目錄中,以便 Gradle 和 IDE 可以自動使用它。版本目錄應提交至原始碼控制:gradle/libs.versions.toml

宣告您的相依性

若要將相依性新增至您的專案,請在 build.gradle(.kts) 檔案的相依性區塊中指定相依性。

下列 build.gradle.kts 檔案使用上述版本目錄,將外掛程式和兩個相依性新增至專案

plugins {
   alias(libs.plugins.androidApplication)  (1)
}

dependencies {
    // Dependency on a remote binary to compile and run the code
    implementation(libs.googleMaterial)    (2)

    // Dependency on a remote binary to compile and run the test code
    testImplementation(libs.mockitoCore)   (3)
}
1 將 Android Gradle 外掛程式套用至這個專案,這會新增數個專門用於建置 Android 應用程式的功能。
2 將 Material 相依性新增至專案。Material Design 提供元件,用於在 Android 應用程式中建立使用者介面。這個函式庫會用於編譯和執行這個專案中的 Kotlin 原始碼。
3 將 Mockito 相依性新增至專案。Mockito 是用於測試 Java 程式碼的模擬架構。這個函式庫會用於編譯和執行這個專案中的測試原始碼。

Gradle 中的相依性會依組態進行分組。

  • material 函式庫會新增至 implementation 組態,這個組態用於編譯和執行生產程式碼。

  • mockito-core 函式庫會新增至 testImplementation 組態,這個組態用於編譯和執行測試程式碼。

還有許多其他可用的組態。

檢視專案相依性

您可以使用 ./gradlew :app:dependencies 指令在終端機中檢視您的相依性樹狀結構

$ ./gradlew :app:dependencies

> Task :app:dependencies

------------------------------------------------------------
Project ':app'
------------------------------------------------------------

implementation - Implementation only dependencies for source set 'main'. (n)
\--- com.google.android.material:material:1.1.0-alpha05 (n)

testImplementation - Implementation only dependencies for source set 'test'. (n)
\--- org.mockito:mockito-core:2.16.0 (n)

...

請參閱 相依性管理章節 以深入了解。

下一步: 深入了解任務 >>