Gradle:如何在java-platform插件中声明Java版本?
用Java Platform插件集中管理多模块配置
Java Platform插件不仅能统一依赖版本,还能通过预编译脚本插件或平台模块的扩展配置,把Java/Kotlin语言版本、仓库、分辨率策略等通用配置集中管控,实现真正的"平台级"统一管理。下面是具体实现方案:
1. 基础平台模块搭建(含依赖版本声明)
先创建platform子模块,配置build.gradle.kts(Groovy DSL逻辑一致,语法稍作调整即可):
plugins { `java-platform` `maven-publish` } javaPlatform { allowDependencies() // 可选,允许平台直接声明依赖用于强制统一版本 } dependencies { constraints { api("com.fasterxml.jackson.core:jackson-databind:2.15.2") api("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.9.0") api("org.springframework.boot:spring-boot-starter-web:3.1.2") } }
2. 集中定义Java/Kotlin语言版本
在平台模块中创建预编译脚本插件(比如src/main/kotlin/my-platform.java-conventions.gradle.kts),统一语言相关配置:
plugins { java kotlin("jvm") apply false } java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } tasks.withType<JavaCompile> { options.encoding = "UTF-8" options.compilerArgs.add("-Xlint:all") } // Kotlin语言配置(按需启用) plugins.withType<org.jetbrains.kotlin.gradle.plugin.KotlinJvmPlugin> { kotlin { jvmToolchain(17) languageVersion = "1.9" apiVersion = "1.9" } }
3. 统一配置Resolution Strategy
在平台的主配置或预编译脚本中添加分辨率策略,确保依赖版本一致性:
configurations.all { resolutionStrategy { // 强制使用平台声明的指定依赖版本 eachDependency { if (requested.group == "com.fasterxml.jackson.core") { useVersion("2.15.2") } } // 动态版本缓存时长 cacheDynamicVersionsFor(10, "minutes") // 优先选择最新稳定版 preferLatestRelease() } }
4. 统一管理仓库
创建src/main/kotlin/my-platform.repositories.gradle.kts脚本,集中定义仓库源:
repositories { mavenCentral() mavenLocal() // 私有仓库(按需添加) maven { url = uri("https://your-private-repo.com/maven") } }
5. 自定义可复用函数
在平台模块的预编译脚本中添加自定义函数,供子模块快速复用:
// 自定义函数:一键添加通用测试依赖 fun DependencyHandlerScope.addTestDependencies() { testImplementation("org.junit.jupiter:junit-jupiter-api:5.9.3") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.3") testImplementation("org.jetbrains.kotlin:kotlin-test-junit5:1.9.0") }
6. 子模块应用平台配置
子模块只需引入平台的脚本插件和依赖约束,即可复用所有统一配置:
plugins { java kotlin("jvm") // 应用平台的通用配置脚本 id("my-platform.java-conventions") id("my-platform.repositories") } dependencies { // 引入平台的依赖版本约束 implementation(platform(project(":platform"))) // 直接使用依赖,无需手动指定版本 implementation("com.fasterxml.jackson.core:jackson-databind") implementation("org.springframework.boot:spring-boot-starter-web") // 调用自定义函数添加测试依赖 addTestDependencies() }
关键说明
- 预编译脚本插件是Gradle实现配置复用的最佳方式,平台模块编译后会生成可复用的插件JAR,子模块直接引用即可生效。
- 若使用Groovy DSL,只需将上述Kotlin代码转换为Groovy语法,核心逻辑完全一致。
内容的提问来源于stack exchange,提问作者Pavel Niedoba
相关产品推荐
相关产品推荐

