- 使用
dependencyManagement
插件:
- 在根目录的
build.gradle.kts
(Kotlin DSL)文件中,应用io.spring.dependency-management
插件(如果是Java项目通常用于Spring Boot项目管理依赖版本,但也可用于通用依赖版本管理)。例如:
plugins {
id("io.spring.dependency-management") version "1.1.0" apply false
}
- 在需要管理依赖的模块(例如
app
模块的build.gradle.kts
)中应用该插件:
plugins {
id("io.spring.dependency-management")
// 假设这是一个Kotlin应用模块,还可能有kotlin - jvm等插件
kotlin("jvm") version "1.8.20"
application
}
- 在
dependencyManagement
块中定义依赖版本。例如,管理okhttp
库的版本:
dependencyManagement {
dependencies {
dependency("com.squareup.okhttp3:okhttp:4.10.0")
}
}
- 然后在
dependencies
块中引入依赖时,无需指定版本:
dependencies {
implementation("com.squareup.okhttp3:okhttp")
}
- 使用
platform
(BOM - Bill of Materials):
- 引入BOM依赖。例如,对于Spring Boot项目,可以引入Spring Boot的BOM:
dependencies {
implementation(platform("org.springframework.boot:spring - boot - dependencies:3.0.5"))
implementation("org.springframework.boot:spring - boot - starter - web")
}
- 这里
platform
指定了一个BOM,spring - boot - starter - web
依赖会从该BOM中获取版本,避免手动指定版本引发的冲突。
- 统一版本定义:
- 在根目录的
build.gradle.kts
中定义一个ext
块来集中管理版本。例如:
ext {
set("okhttpVersion", "4.10.0")
}
- 在模块的
build.gradle.kts
中使用这个版本定义:
dependencies {
implementation("com.squareup.okhttp3:okhttp:${rootProject.ext["okhttpVersion"]}")
}
- 排除传递依赖:
- 假设引入了一个库,它传递依赖了某个库的不兼容版本。例如,
libraryA
依赖了libraryB:1.0
,而项目中需要libraryB:2.0
。可以排除libraryA
对libraryB:1.0
的传递依赖:
dependencies {
implementation("com.example:libraryA") {
exclude(group = "com.example.dependency", module = "libraryB")
}
implementation("com.example.dependency:libraryB:2.0")
}