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

如何创建可被其他模块buildscript类路径引用的Gradle模块

问题

我需要在项目中实现一个子项目生成的Jar包可被另一个子项目的buildscript类路径引用。了解到需使用复合构建来实现,尝试按如下结构组织项目:

root
   test
   test2

根目录的settings.gradle.kts配置如下:

include("test")
includeBuild("test2")

test项目的build.gradle.kts配置:

plugins {
    kotlin("jvm") version "1.7.10"
}

group = "github.fatalcatharsis"
version = "1.0-SNAPSHOT"

复合构建的test2/settings.gradle.kts配置:

includeBuild("..") {
    dependencySubstitution {
        substitute(module("github.fatalcatharsis:test")).using(project(":test"))
    }
}

将其作为compile依赖时代替生效正常,比如test2/build.gradle.kts配置:

plugins {
    kotlin("jvm") version "1.7.10"
}

group = "github.fatalcatharsis"
version = "1.0-SNAPSHOT"

dependencies {
    implementation("github.fatalcatharsis:test:1.0-SNAPSHOT")
}

但将其作为buildscript依赖时,提示无法在任何仓库中找到外部依赖,配置如下:

buildscript {
    dependencies {
        classpath("github.fatalcatharsis:test:1.0-SNAPSHOT")
    }
}

plugins {
    kotlin("jvm") version "1.7.10"
}

group = "github.fatalcatharsis"
version = "1.0-SNAPSHOT"

请问如何实现让一个模块可被另一个模块的buildscript类路径引用?

解决方案

默认复合构建的依赖替换仅作用于项目常规依赖(如implementation),要让buildscript类路径也能解析另一个子项目的Jar,需在复合构建的settings配置中显式为buildscript配置依赖替换,具体步骤如下:

  1. 修改test2/settings.gradle.kts,添加buildscript的依赖替换配置:
includeBuild("..") {
    dependencySubstitution {
        // 替换常规项目依赖
        substitute(module("github.fatalcatharsis:test")).using(project(":test"))
    }
    // 为buildscript配置依赖替换
    buildscriptConfiguration {
        dependencies {
            classpath(project(":test"))
        }
    }
}

配置完成后,test2的buildscript中使用classpath("github.fatalcatharsis:test:1.0-SNAPSHOT")时,Gradle会自动替换为:test项目的输出Jar。

  1. 确保test项目的配置正确:
    test项目需启用kotlin-jvm(或java)插件,保证能生成可被引用的Jar产物。如果有自定义Jar任务,需将该任务的产物标记为可用于buildscript类路径。

备选方案:本地仓库发布

如果复合构建方案未生效,可通过本地Maven仓库间接引用:

  • 在test项目的build.gradle.kts中添加maven-publish插件:
plugins {
    kotlin("jvm") version "1.7.10"
    `maven-publish`
}

publishing {
    publications {
        create<MavenPublication>("maven") {
            from(components["java"])
        }
    }
    repositories {
        mavenLocal()
    }
}
  • 执行./gradlew publishToMavenLocal将test的Jar发布到本地仓库
  • 在test2的build.gradle.kts的buildscript中配置本地仓库:
buildscript {
    repositories {
        mavenLocal()
    }
    dependencies {
        classpath("github.fatalcatharsis:test:1.0-SNAPSHOT")
    }
}

优先推荐复合构建方案,更适配多模块协作场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 06:18:24