Appearance
子项目配置
allprojects vs subprojects
kotlin
// 根项目 build.gradle.kts
// allprojects:配置根项目 + 所有子项目
allprojects {
group = "com.example"
version = "1.0.0"
repositories {
mavenCentral()
}
}
// subprojects:只配置子项目(不含根项目)
subprojects {
apply(plugin = "java")
java {
sourceCompatibility = JavaVersion.VERSION_17
}
tasks.withType<Test> {
useJUnitPlatform()
}
dependencies {
"testImplementation"("org.junit.jupiter:junit-jupiter:5.10.1")
}
}针对特定子项目配置
kotlin
// 方式一:project() 块(简单)
project(":web") {
apply(plugin = "org.springframework.boot")
dependencies {
"implementation"("org.springframework.boot:spring-boot-starter-web:3.2.0")
}
}
// 方式二:在子项目自己的 build.gradle.kts 中配置(推荐)
// 每个子项目管理自己的特定配置使用约定插件(Convention Plugin)
比 subprojects {} 更灵活的方式是使用约定插件(在 buildSrc 或 build-logic 模块中定义):
kotlin
// buildSrc/src/main/kotlin/java-conventions.gradle.kts
plugins {
java
checkstyle
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
checkstyle {
toolVersion = "10.12.5"
configFile = rootProject.file("config/checkstyle.xml")
}
tasks.withType<Test> {
useJUnitPlatform()
}
dependencies {
testImplementation("org.junit.jupiter:junit-jupiter:5.10.1")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}kotlin
// 子项目 build.gradle.kts - 只需应用约定插件
plugins {
id("java-conventions")
}子项目间的公共配置管理
kotlin
// 根项目 build.gradle.kts
// 统一代码检查配置
subprojects {
apply(plugin = "checkstyle")
configure<CheckstyleExtension> {
toolVersion = "10.12.5"
configFile = rootProject.file("config/checkstyle.xml")
maxWarnings = 0
}
}
// 统一 JAR 配置
subprojects {
tasks.withType<Jar> {
manifest {
attributes("Built-By" to System.getProperty("user.name"))
}
}
}类型安全的项目引用
在 settings.gradle.kts 中启用:
kotlin
enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS")然后使用:
kotlin
// 代替 implementation(project(":core"))
dependencies {
implementation(projects.core)
implementation(projects.service.auth)
}