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

如何在构建与运行时为groovy-gradle-plugin传递不同参数?

解决Gradle插件编译与运行时参数传递问题

一、设置编译时参数build_version

这个参数在插件编译阶段确定,可用于依赖声明或嵌入插件代码,推荐以下两种实现方式:

1. 用gradle.properties直接定义

在build-logic/commons目录下创建或编辑gradle.properties文件,添加:

build_version=1.0

之后在该模块的build.gradle中直接引用变量即可:

plugins {
    id('java')
}

group = 'com.example.myproduct'

dependencies {
    implementation(platform("com.example.platform:product-platform:${build_version}"))
}

2. 将版本号编译进插件代码

如果需要把build_version嵌入插件运行时可读取的位置,比如插件内部展示版本,可通过资源文件替换实现:

  • 在src/main/resources下创建plugin.properties:
    plugin.version=${build_version}
    
  • 在build.gradle中配置processResources任务自动替换变量:
    processResources {
        expand(build_version: build_version)
    }
    

插件代码中即可通过读取该properties文件获取版本号。

二、设置运行时参数run_version

这个参数由应用插件的项目在运行时指定,需通过插件扩展实现配置接收:

1. 在插件代码中定义扩展类

假设你的插件类为MyProductPlugin,添加扩展让用户配置run_version:

class MyProductPlugin implements Plugin<Project> {
    void apply(Project project) {
        // 创建扩展,用户可通过myProduct.run_version配置
        def extension = project.extensions.create('myProduct', MyProductExtension)
        
        // 延迟配置测试依赖,确保用户已完成扩展配置
        project.afterEvaluate {
            project.dependencies {
                testImplementation(platform("com.example.platform:test-platform:${extension.run_version}"))
            }
        }
    }
}

class MyProductExtension {
    String run_version
}

2. 应用插件时传递参数

其他项目引入插件后,在自身build.gradle中配置扩展即可:

plugins {
    id('com.example.myproduct.commons')
}

myProduct {
    run_version = "2.0"
}

3. 可选:支持命令行临时传递参数

若需临时通过命令行指定run_version,可在插件中读取项目属性:

void apply(Project project) {
    def runVersion = project.findProperty('run_version') ?: '1.0' // 设置默认值
    project.dependencies {
        testImplementation(platform("com.example.platform:test-platform:${runVersion}"))
    }
}

用户运行时通过./gradlew build -Prun_version=2.0传递参数即可。

三、排查之前ext配置失效的原因

你之前用ext定义变量未生效,大概率是作用域问题:build-logic作为独立的构建模块,ext变量的作用域仅限当前脚本局部,且若定义位置晚于依赖声明代码,就会出现读取不到的情况。优先使用gradle.properties能避免这类作用域问题,变量读取更稳定。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 22:02:09