
在 Kotlin Multiplatform 项目中,自定义 Gradle 属性(如 Attribute.of("custom", String::class.java))不会自动跨模块传播;消费者必须在每一级依赖声明处显式指定属性值,否则 Gradle 无法唯一匹配变体,导致构建失败。
在 kotlin multiplatform 项目中,自定义 gradle 属性(如 `attribute.of("custom", string::class.java)`)不会自动跨模块传播;消费者必须在每一级依赖声明处显式指定属性值,否则 gradle 无法唯一匹配变体,导致构建失败。
当使用自定义属性区分同一平台下的多个目标(例如 jvm 和 jvm("custom"))时,Gradle 的变体选择机制遵循消费者主导(consumer-driven)原则:属性匹配是逐跳(hop-by-hop)进行的,而非“穿透式”继承。这意味着,即使顶层 JVM 消费者 :parent 在依赖 :sub2 时指定了 attribute(customAttribute, "customValue"),该属性不会自动向下传递给 :sub2 对 :sub1 的依赖——:sub2 仍需独立为 :sub1 声明匹配的属性,否则 Gradle 在解析 :sub1 的可用变体(如 jvmApiElements、customApiElements)时将面临歧义,抛出 “Could not resolve project” 错误。
✅ 正确做法:按源集(SourceSet)粒度精准绑定属性
关键在于:每个源集(source set)应只依赖与其语义一致的变体。例如,若 :sub2 定义了 customMain 源集用于启用定制逻辑,则它对 :sub1 的依赖也必须显式限定为 "customValue" 变体:
// :sub2/build.gradle.kts
val customAttribute = Attribute.of("custom", String::class.java)
kotlin {
jvm { /* ... */ }
jvm("custom") { /* ... */ }
sourceSets {
// ✅ 为 normal 主源集绑定 normal 变体
val jvmMain by getting {
dependencies {
api(project(":sub1")) {
attributes {
attribute(customAttribute, "normal") // ← 显式指定
}
}
}
}
// ✅ 为 custom 主源集绑定 customValue 变体
val customMain by getting {
dependencies {
api(project(":sub1")) {
attributes {
attribute(customAttribute, "customValue") // ← 显式指定
}
}
}
}
}
}同时,:parent(JVM 项目)也需确保其依赖 :sub2 时,所选变体与 :sub2 中 customMain 源集的输出相匹配(即 :sub2 的 customApiElements 变体):
// :parent/build.gradle.kts
dependencies {
implementation(project(":sub2")) {
attributes {
attribute(customAttribute, "customValue") // ← 匹配 :sub2 的 custom 变体
}
}
}⚠️ 注意事项:
- 不可省略中间层声明:
:sub2必须主动为:sub1设置属性,不能依赖:parent的设置“透传”;- 属性定义需全局一致:所有模块中
Attribute.of("custom", String::class.java)的创建方式必须完全相同(推荐抽取为 Gradle 共享常量或插件);- 避免在 commonMain 中声明跨变体依赖:
commonMain.dependencies { api(project(":sub1")) }会导致 Gradle 无法推断目标变体,应拆分至平台专属源集(如jvmMain/customMain);- 验证变体可用性:可通过
./gradlew :sub1:dependencies --configuration jvmApiElements查看:sub1发布的变体及其属性。
? 总结
Gradle 的多变体依赖解析本质是契约式匹配:每个依赖声明都是一个独立的“请求”,需明确告知 Gradle “我要哪一个变体”。KMM 中的自定义属性不是配置继承机制,而是变体筛选标签。要实现端到端的定制变体链路(:parent → :sub2 → :sub1),必须在每一级 project(...) 依赖块中显式、精确地重复声明相同属性值。这是设计使然,而非缺陷——它保障了构建的确定性与可预测性。


















