/* * 第 6 章 · 依赖管理演示 — build.gradle.kts * * 跑下面这些命令查看效果: * ./gradlew dependencies * ./gradlew dependencies --configuration runtimeClasspath * ./gradlew dependencyInsight --dependency guava * ./gradlew showDeps —— 自定义任务,打印依赖类型 */ plugins { `java-library` // 必须用 java-library 才能用 api } group = "com.example.gradle.dep" version = "1.0.0" repositories { mavenCentral() } dependencies { // ===== 1. implementation:编译+运行可见,不传递 ===== implementation("com.google.guava:guava:32.1.3-jre") implementation("org.slf4j:slf4j-api:2.0.9") // ===== 2. api:传递给消费者 ===== api("org.apache.commons:commons-lang3:3.13.0") // ===== 3. compileOnly:仅编译需要 ===== compileOnly("org.projectlombok:lombok:1.18.30") annotationProcessor("org.projectlombok:lombok:1.18.30") // ===== 4. runtimeOnly:仅运行需要 ===== runtimeOnly("ch.qos.logback:logback-classic:1.4.11") // ===== 5. testImplementation ===== testImplementation("org.junit.jupiter:junit-jupiter:5.10.0") testImplementation("org.assertj:assertj-core:3.24.2") testRuntimeOnly("org.junit.platform:junit-platform-launcher") // ===== 6. 排除传递依赖示例 ===== implementation("org.springframework:spring-context:6.1.1") { exclude(group = "commons-logging", module = "commons-logging") } // ===== 7. platform / BOM 演示 ===== // implementation(platform("org.springframework:spring-framework-bom:6.1.1")) // implementation("org.springframework:spring-web") // 不用写版本 // ===== 8. 强制版本演示 ===== // implementation("com.google.guava:guava") { // version { strictly("30.0") } // } } // ===== 9. 全局 force / exclude ===== configurations.all { // resolutionStrategy.force("com.google.guava:guava:32.1.3-jre") exclude(group = "junit", module = "junit") // 排除老 JUnit 4 的传递依赖 } // ===== 10. 自定义任务:打印依赖统计 ===== tasks.register("showDeps") { group = "ch06-demo" description = "打印各 configuration 的依赖数" doLast { listOf( "implementation", "api", "compileOnly", "runtimeOnly", "testImplementation", "compileClasspath", "runtimeClasspath", "testRuntimeClasspath" ).forEach { name -> val cfg = configurations.findByName(name) if (cfg != null) { val direct = cfg.dependencies.size val resolved = if (cfg.isCanBeResolved) cfg.resolvedConfiguration.firstLevelModuleDependencies.size else -1 println(String.format("%-25s direct=%2d resolved-direct=%s", name, direct, if (resolved >= 0) resolved.toString() else "(non-resolvable)")) } } } } tasks.test { useJUnitPlatform() }