为 Gradle 项目声明的每个依赖项都适用于特定范围。
例如,某些依赖项应用于编译源代码,而其他依赖项只需在运行时可用即可
dependencies {
implementation("com.google.guava:guava:30.0-jre") // Needed to compile and run the app
runtimeOnly("org.slf4j:slf4j-simple:2.0.13") // Only needed at runtime
}
dependencies {
implementation("com.google.guava:guava:30.0-jre") // Needed to compile and run the app
runtimeOnly("org.slf4j:slf4j-simple:2.0.13") // Only needed at runtime
}
依赖配置是一种在项目内为不同目的定义不同依赖项集合的方式。它们决定了依赖项在构建过程的各个阶段如何以及何时使用。
配置是 Gradle 依赖解析的基础部分。
理解依赖配置
Gradle 借助 Configuration 表示依赖项的作用域。每个配置都可以通过唯一名称进行识别。
许多 Gradle 插件会为您的项目添加预定义配置。
Java Library 插件用于定义产生 Java 库的项目。该插件添加了许多依赖配置。这些配置代表了源代码编译、测试执行等所需的各种类路径。
配置名称 | 描述 | 用途 |
---|---|---|
|
编译和运行时都需要,并包含在发布的 API 中。 |
声明依赖项 |
|
编译和运行时都需要。 |
声明依赖项 |
|
仅在编译时需要,不包含在运行时或发布中。 |
声明依赖项 |
|
仅在编译时需要,但包含在发布的 API 中。 |
声明依赖项 |
|
仅在运行时需要,不包含在编译类路径中。 |
声明依赖项 |
|
编译和运行测试所需依赖项。 |
声明依赖项 |
|
仅在测试编译时需要依赖项。 |
声明依赖项 |
|
仅在运行测试时需要依赖项。 |
声明依赖项 |
依赖项声明配置
依赖项声明配置(compileOnly
、implementation
、runtimeOnly
)侧重于根据依赖项的用途(编译时、运行时、API 暴露)来声明和管理依赖项
dependencies {
implementation("com.google.guava:guava:30.1.1-jre") // Implementation dependency
compileOnly("org.projectlombok:lombok:1.18.20") // Compile-only dependency
runtimeOnly("mysql:mysql-connector-java:8.0.23") // Runtime-only dependency
}
dependencies {
implementation("com.google.guava:guava:30.1.1-jre") // Implementation dependency
compileOnly("org.projectlombok:lombok:1.18.20") // Compile-only dependency
runtimeOnly("mysql:mysql-connector-java:8.0.23") // Runtime-only dependency
}
其他配置
还有其他类型的配置(如 runtimeClasspath
、compileClasspath
、apiElements
、runtimeElements
),但它们不用于声明依赖项。
也可以创建自定义配置。自定义配置允许您定义一组不同的依赖项,这些依赖项可用于特定目的,例如工具链或代码生成,与标准配置(例如 implementation
、testImplementation
)分开。
val customConfig by configurations.creating
dependencies {
customConfig("org.example:example-lib:1.0")
}
configurations {
customConfig
}
dependencies {
customConfig("org.example:example-lib:1.0")
}
创建自定义配置有助于管理和隔离依赖项,确保它们仅包含在相关的类路径和构建过程中。
查看配置
dependencies
task 提供了项目依赖项的概述。要关注某个依赖配置的信息,请提供可选参数 --configuration
。
以下示例显示了 Java 项目的 implementation
依赖配置中的依赖项
$ ./gradlew -q app:dependencies --configuration implementation
------------------------------------------------------------
Project ':app'
------------------------------------------------------------
implementation - Implementation only dependencies for source set 'main'.
\--- com.google.guava:guava:30.0-jre
下一步: 了解声明仓库 >>