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

如何在Gradle Application Plugin中追加外部VM参数

解决Gradle Application Plugin外部VM参数不生效的问题

Gradle的run任务默认不会将命令行传入的-D类系统属性传递给启动的应用程序进程——这些参数属于Gradle自身的JVM实例,而非目标应用的JVM。要实现外部VM参数追加到applicationDefaultJvmArgs的需求,需要通过修改run任务的配置,显式将外部参数传递给应用进程。

方案1:传递所有外部传入的系统属性

如果希望将所有通过命令行(或IntelliJ Gradle配置)传入的-D参数都追加到应用的JVM参数中,可以直接将Gradle进程的系统属性同步到应用进程:

Groovy DSL(build.gradle)

tasks.named('run') {
    // 先加载applicationDefaultJvmArgs中的系统属性,再追加外部传入的属性(外部属性不会覆盖默认值)
    def defaultSystemProps = applicationDefaultJvmArgs.findAll { it.startsWith('-D') }.collectEntries {
        def prop = it.substring(2).split('=', 2)
        [(prop[0]): prop.length > 1 ? prop[1] : '']
    }
    systemProperties defaultSystemProps
    systemProperties.putAll(System.getProperties())
}

Kotlin DSL(build.gradle.kts)

tasks.named<JavaExec>("run") {
    val defaultSystemProps = applicationDefaultJvmArgs
        .filter { it.startsWith("-D") }
        .associate {
            val prop = it.substring(2).split("=", limit = 2)
            prop[0] to if (prop.size > 1) prop[1] else ""
        }
    systemProperties(defaultSystemProps)
    systemProperties.putAll(System.getProperties())
}

如果不需要保留applicationDefaultJvmArgs的优先级(允许外部参数覆盖默认值),可以简化为:

// Groovy简化版
tasks.named('run') {
    systemProperties System.getProperties()
}

方案2:只传递指定的外部参数

如果仅需要传递特定的参数(比如只处理foo参数),可以针对性提取并添加:

Groovy DSL

tasks.named('run') {
    def fooValue = System.getProperty('foo')
    if (fooValue != null) {
        // 直接添加为JVM参数,与applicationDefaultJvmArgs合并
        jvmArgs "-Dfoo=${fooValue}"
    }
}

Kotlin DSL

tasks.named<JavaExec>("run") {
    System.getProperty("foo")?.let {
        jvmArgs("-Dfoo=$it")
    }
}

验证方式

配置完成后,执行命令测试:

gradle run -Dfoo=bar

在应用代码中通过System.getProperty("foo")即可获取到bar的值,同时applicationDefaultJvmArgs中配置的参数也会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 22:47:50