如何使用GroovyShell传递JVM参数和脚本参数? [英] How to pass JVM arguments and script argument using GroovyShell?
问题描述
所以我有一个Groovy脚本:
So I have a Groovy script:
// TestScript.groovy
println args
然后在我执行的Gradle任务中
Then in a Gradle task I have
test {
String profile = System.getenv("spring.profiles.active")
jvmArgs '-Dspring.profiles.active=$profile" // THIS DOES NOT WORK! :(
doLast {
new GroovyShell().run(file('package.TestScript.groovy'))
}
}
我需要做的两件事:
a)传递到 TestScript.groovy
程序参数中,以便打印出 args
数组
a) Pass into TestScript.groovy
program arguments so it will print out the args
array
b)将Spring Boot配置文件传递给JVM,即 spring.profiles.active = dev
b) Pass to JVM the Spring Boot profile i.e. spring.profiles.active=dev
有什么建议吗?
Note, I'm using Groovy 2.4.3 and referring to this documentation: http://docs.groovy-lang.org/2.4.3/html/api/groovy/lang/GroovyShell.html
我尝试了以下失败的事情:
I tried the following which was unsuccessful:
doLast {
Binding b = new Binding();
b.setVariable('spring.profiles.active', $profile)
new GroovyShell(b).run(file('package.TestScript.groovy'))
}
推荐答案
工作示例这里 ...
如果我们有一个将参数写入文件的脚本:
If we have a script that writes arguments to a file:
// TestScript.groovy
try {
new File("out.txt").withWriter { writer ->
args.each { arg ->
writer.write("TRACER arg : ${arg}\n")
}
}
} catch (Exception ex) {
new File("error.txt").withWriter { writer ->
writer.write("TRACER caught exception ${ex.message}\n")
}
}
然后我们可以使用此Gradle任务对其进行测试:
then we can test it with this Gradle task:
test {
doLast {
def profile = project["spring.profiles.active"]
def script = new File("${projectDir}/TestScript.groovy")
def args = ["exampleArgVal1", "exampleArgVal2", profile]
new GroovyShell().run(script, args)
}
}
请注意,像这样将参数传递给Gradle:
Note that parameters are passed to Gradle like so:
gradle clean test -Pspring.profiles.active=TEST_PROFILE
这篇关于如何使用GroovyShell传递JVM参数和脚本参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!