Gradle 內建支援依賴管理。

依賴管理是一種自動化技術,用於宣告和解析專案所需的外部資源。
Gradle 建置腳本定義了建置專案的流程,這些專案可能需要外部依賴關係。依賴關係指的是支援建置專案的 JAR 檔、外掛、函式庫或原始碼。
版本目錄
版本目錄提供了一種在 libs.versions.toml
檔案中集中管理依賴關係宣告的方式。
此目錄使子專案之間共享依賴關係和版本配置變得簡單。它還允許團隊在大型專案中強制執行函式庫和外掛的版本。
版本目錄通常包含四個區段:
-
[versions] 用於宣告外掛和函式庫將參考的版本號。
-
[libraries] 用於定義建置檔案中使用的函式庫。
-
[bundles] 用於定義一組依賴關係。
-
[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)
檔案的 dependencies 區塊中指定依賴關係。
以下 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 程式碼的模擬框架。此函式庫將用於編譯和執行此專案中的 test 原始碼。 |
Gradle 中的依賴關係依組態分組。
-
material
函式庫已新增至implementation
組態,該組態用於編譯和執行生產程式碼。 -
mockito-core
函式庫已新增至testImplementation
組態,該組態用於編譯和執行 test 程式碼。
還有更多可用的組態。 |
檢視專案依賴關係
您可以使用 ./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)
...
請參閱依賴管理章節以瞭解更多資訊。
下一步: 瞭解任務 >>