Gradle 参数传递方式详解
📌 一、基础参数传递方式
1. 项目属性(-P
)
通过 -Pkey=value
传递参数,适用于自定义任务逻辑:
task printConfig {
doLast {
def env = project.hasProperty('env') ? project.env : 'dev'
println "Environment: $env"
}
}
执行命令:gradle printConfig -Penv=prod
- 优势:作用域限定在 Gradle 项目内,不污染 JVM 环境。
2. 系统属性(-D
)
通过 -Dkey=value
传递全局 JVM 系统属性:
task checkSystemProp {
doLast {
def threadCount = System.getProperty('threads') ?: '4'
println "Threads: $threadCount"
}
}
执行命令:gradle checkSystemProp -Dthreads=8
- 注意:属性在整个 JVM 生命周期有效。
🔧 二、Java 应用参数传递
1. JavaExec
任务动态参数
在自定义任务中处理多参数:
task runApp(type: JavaExec) {
mainClass = 'com.example.Main'
classpath = sourceSets.main.runtimeClasspath
if (project.hasProperty('appArgs')) {
args appArgs.split(',')
}
}
执行命令:gradle runApp -PappArgs="arg1,arg2"
。
2. Application 插件(Gradle 4.9+)
使用内置 --args
传递参数:
plugins { id 'application' }
application { mainClass = 'com.example.Main' }
执行命令:gradle run --args="arg1 arg2"
。
🧩 三、复杂数据处理
1. 列表类型参数
解析逗号分隔的列表:
task processItems {
doLast {
def items = project.hasProperty('items') ? project.items.split(',') : []
items.each { println "Item: $it" }
}
}
执行命令:gradle processItems -Pitems=apple,orange
。
2. JSON 参数解析
使用 JsonSlurper
处理结构化数据:
task parseJson {
doLast {
def json = project.hasProperty('json') ? project.json : '{}'
def data = new groovy.json.JsonSlurper().parseText(json)
println "User: ${data.name}"
}
}
执行命令:gradle parseJson -Pjson='{"name":"John"}'
。
🔐 四、安全与混合方案
1. 环境变量结合参数
敏感数据(如 API Key)通过环境变量传递:
task fetchData {
doLast {
def apiKey = System.getenv('API_KEY')
def endpoint = project.hasProperty('endpoint') ? project.endpoint : '/default'
println "Endpoint: $endpoint, Key: $apiKey"
}
}
执行命令:export API_KEY=123; gradle fetchData -Pendpoint=/users
。
2. 加密参数管理
建议结合 AWS KMS 或 Vault 动态解密参数,避免硬编码。
⚙️ 五、高级技巧
1. 自定义命令行选项(Gradle 6.0+)
使用 @Option
注解创建友好 CLI 接口:
open class PrintPet : DefaultTask() {
@set:Option(option = "pet", description = "宠物名称")
var pet: String = ""
@TaskAction
fun print() {
println("$pet is awesome!")
}
}
tasks.register<PrintPet>("printPet")
执行命令:gradle printPet --pet="Cat"
。
2. 多环境配置
动态加载不同环境的资源文件:
processResources {
filesMatching('application.properties') {
filter(ReplaceTokens, tokens: [
DB_URL: project.hasProperty('dbUrl') ? project.dbUrl : 'jdbc:default'
])
}
}
执行命令:gradle build -PdbUrl=jdbc:prod
。
💎 总结:方案对比与选型
场景 | 推荐方案 | 示例命令 |
---|---|---|
简单键值对 | 项目属性 (-P ) | gradle task -Pkey=value |
Java 应用多参数 | --args (Gradle 4.9+) | gradle run --args="arg1 arg2" |
敏感数据 | 环境变量 + 项目属性 | export KEY=val; gradle task -Pparam |
结构化数据 (JSON/列表) | 反序列化 + -P | gradle task -Pjson='{...}' |
自定义 CLI 交互 | @Option 注解 | gradle task --customArg=value |
提示:优先使用项目属性(
-P
)避免全局污染,复杂数据结合 Groovy 脚本处理,敏感信息务必通过环境变量或加密工具管理。