在Gradle项目中,dependencyManagement 块用于集中管理项目的依赖版本,确保所有子模块使用相同的依赖版本。这有助于避免版本冲突和依赖混乱。
dependencyManagement 的作用
集中管理依赖版本:
在多模块项目中,可以集中管理所有子模块的依赖版本。
避免每个子模块单独指定依赖版本,从而减少版本冲突。
简化子模块依赖声明:
子模块只需要声明依赖名称,而不必指定版本号。
示例代码
假设您有一个多模块的Gradle项目,最外层的 build.gradle 文件中包含 dependencyManagement 块:
plugins {
id 'org.springframework.boot' version '2.7.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}
dependencyManagement {
dependencies {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-dependencies:2021.0.1'
}
dependency 'org.springframework.boot:spring-boot-starter-web'
dependency 'org.springframework.boot:spring-boot-starter-data-jpa'
dependency 'org.springframework.boot:spring-boot-starter-test'
}
}
imports 块:imports 块用于导入外部的 BOM(Bill of Materials)。
例如,mavenBom 'org.springframework.cloud:spring-cloud-dependencies:2021.0.1' 导入 Spring Cloud 的依赖管理 BOM。
dependency 块:dependency 块用于指定具体的依赖项及其版本。
例如,dependency 'org.springframework.boot:spring-boot-starter-web' 指定了 spring-boot-starter-web 依赖。
假设您的项目结构如下:
my-project/
├── build.gradle
├── settings.gradle
└── submodules/
├── module1/
│ └── build.gradle
└── module2/
└── build.gradle
build.gradle 文件(最外层)
plugins {
id 'org.springframework.boot' version '2.7.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}
dependencyManagement {
dependencies {
imports {
mavenBom 'org.springframework.cloud:spring-cloud-dependencies:2021.0.1'
}
dependency 'org.springframework.boot:spring-boot-starter-web'
dependency 'org.springframework.boot:spring-boot-starter-data-jpa'
dependency 'org.springframework.boot:spring-boot-starter-test'
}
}
module1/build.gradle 文件
plugins {
id 'org.springframework.boot' version '2.7.4'
id 'java'
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
runtimeOnly 'mysql:mysql-connector-java'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
dependencyManagement:集中管理依赖版本,避免版本冲突。
imports 块:导入外部的 BOM,简化依赖管理。
dependency 块:指定具体的依赖项及其版本。
这样可以确保所有子模块使用相同的依赖版本,提高项目的可维护性和稳定性。