You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

模块化Gradle构建逻辑极简配置下Kotlin插件重复加载问题

问题分析:Kotlin Gradle插件重复加载警告

环境信息

  • Kotlin 1.9.20
  • Gradle 8.4
  • JDK 17

项目结构

├── build-logic
│   ├── kotlin-project
│   │   ├── build.gradle.kts
│   │   └── src
│   │       └── main
│   │           └── kotlin
│   │               └── kotlin-convention.gradle.kts
│   ├── other
│   │   ├── build.gradle.kts
│   │   └── src
│   │       └── main
│   │           └── kotlin
│   │               └── other-convention.gradle.kts
│   └── settings.gradle.kts
├── lib1
│   └── build.gradle.kts
├── lib2
│   └── build.gradle.kts
└── settings.gradle.kts

核心配置说明

主项目settings.gradle.kts

pluginManagement {
    includeBuild("build-logic")
}

rootProject.name = "kotlin-plugin-loaded-multiple-times-example"

include("lib1")
include("lib2")

lib1/build.gradle.kts

plugins {
    id("kotlin-convention")
}

lib2/build.gradle.kts

plugins {
    id("kotlin-convention")
    id("other-convention") // <-- 这是lib1与lib2配置的唯一区别
}

build-logic/settings.gradle.kts

include("kotlin-project")
include("other")

build-logic/kotlin-project/build.gradle.kts

plugins {
    `kotlin-dsl`
}

repositories {
    gradlePluginPortal()
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.20")
}

kotlin-convention.gradle.kts

plugins {
    kotlin("jvm") // <-- 仅应用Kotlin插件
}

repositories {
    mavenCentral()
}

build-logic/other/build.gradle.kts

plugins {
    `kotlin-dsl`
}

repositories {
    gradlePluginPortal()
}

注:other-convention.gradle.kts为空白文件,添加jacoco等插件不影响问题

运行gradle build出现的警告

The Kotlin Gradle plugin was loaded multiple times in different subprojects, which is not supported and may break the build.
This might happen in subprojects that apply the Kotlin plugins with the Gradle 'plugins { ... }' DSL if they specify explicit versions, even if the versions are equal.
Please add the Kotlin plugin to the common parent project or the root project, then remove the versions in the subprojects.
If the parent project does not need the plugin, add 'apply false' to the plugin line.
See: https://docs.gradle.org/current/userguide/plugins.html#sec:subprojects_plugins_dsl
The Kotlin plugin was loaded in the following projects: ':lib1', ':lib2'

问题原因

问题出在构建逻辑组件的隔离性和Gradle插件的类加载机制上:

  • 你把kotlin-convention和other-convention拆分到了两个独立的build-logic子项目(kotlin-project和other)中,这两个子项目会生成各自独立的类加载器环境。
  • 当lib2同时应用这两个约定插件时,kotlin-jvm插件会先通过kotlin-convention所在的类加载器加载一次;而other-convention所在的构建逻辑组件没有依赖kotlin-gradle-plugin,Gradle会在lib2的项目上下文里再次加载Kotlin插件,最终导致重复加载的警告。
  • 当你把other-convention移到kotlin-project里时,两个约定插件共享同一个构建逻辑类加载器,Kotlin插件只会被加载一次;如果移除lib2中的other-convention,lib2和lib1一样只通过kotlin-convention加载一次Kotlin插件,警告就会消失。

本质上就是:独立的构建逻辑组件会创建隔离的类加载环境,跨组件应用插件时,会触发核心依赖插件的多次加载。

内容的提问来源于stack exchange,提问作者Kirill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:17:08