依赖管理
→ 返回构建工具
依赖坐标
Maven/Gradle 通过 GAV 唯一标识一个构件:
groupId:artifactId:version
例:org.springframework.boot:spring-boot-starter-web:3.2.0
Maven 依赖管理
依赖范围(scope)
| scope | 编译 | 测试 | 运行 | 打包 | 说明 |
|---|---|---|---|---|---|
| compile(默认) | ✓ | ✓ | ✓ | ✓ | 最常用 |
| provided | ✓ | ✓ | ✗ | ✗ | 容器提供,如 servlet-api |
| runtime | ✗ | ✓ | ✓ | ✓ | 运行时需要,如 JDBC 驱动 |
| test | ✗ | ✓ | ✗ | ✗ | 仅测试,如 JUnit |
依赖传递与冲突
A → B → C,A 间接依赖 C。
冲突解决规则:
- 最短路径优先:
A→B→C:1.0与A→C:2.0,选C:2.0 - 声明顺序优先:路径相同时,
pom.xml中先声明的优先
排除传递依赖
<dependency>
<groupId>com.example</groupId>
<artifactId>b</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>com.example</groupId>
<artifactId>c</artifactId>
</exclusion>
</exclusions>
</dependency>dependencyManagement
在父 pom 中统一声明版本,子模块无需指定版本:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.2.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>常用命令
mvn dependency:tree # 查看完整依赖树
mvn dependency:analyze # 分析无用/缺失依赖
mvn dependency:resolve # 解析并下载所有依赖Gradle 依赖管理
依赖配置
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web:3.2.0")
testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
compileOnly("org.projectlombok:lombok:1.18.30")
annotationProcessor("org.projectlombok:lombok:1.18.30")
runtimeOnly("com.mysql:mysql-connector-j:8.2.0")
}配置说明
| 配置 | 说明 |
|---|---|
implementation | 编译+运行,不对外暴露(推荐) |
api | 编译+运行,对外暴露(需 java-library 插件) |
compileOnly | 仅编译,如 Lombok |
runtimeOnly | 仅运行,如数据库驱动 |
testImplementation | 仅测试 |
排除传递依赖
implementation("com.example:b:1.0") {
exclude(group = "com.example", module = "c")
}强制指定版本
configurations.all {
resolutionStrategy {
force("com.example:c:2.0")
}
}常用命令
./gradlew dependencies # 查看依赖树
./gradlew :module:dependencies # 指定模块依赖树
./gradlew dependencyInsight --dependency spring-core # 追踪某个依赖来源