英文:
How to pass JVM arguments and script argument using GroovyShell?
问题
以下是翻译好的内容:
所以我有一个Groovy脚本:
// TestScript.groovy
println args
然后在一个Gradle任务中我有:
test {
String profile = System.getenv("spring.profiles.active")
jvmArgs '-Dspring.profiles.active=$profile' // 这个不起作用! :(
doLast {
new GroovyShell().run(file('package.TestScript.groovy'))
}
}
我需要做两件事情:
a) 将程序参数传递给TestScript.groovy
,以便它将打印出args
数组。
b) 将Spring Boot配置文件传递给JVM,即 spring.profiles.active=dev
。
有什么建议吗?
注意,我正在使用Groovy 2.4.3,并参考了这个文档:http://docs.groovy-lang.org/2.4.3/html/api/groovy/lang/GroovyShell.html
我尝试了以下不成功的方法:
doLast {
Binding b = new Binding();
b.setVariable('spring.profiles.active', $profile)
new GroovyShell(b).run(file('package.TestScript.groovy'))
}
英文:
So I have a Groovy script:
// TestScript.groovy
println args
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'))
}
}
What I need to do is two things:
a) Pass into TestScript.groovy
program arguments so it will print out the args
array
b) Pass to JVM the Spring Boot profile i.e. spring.profiles.active=dev
Any suggestions?
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'))
}
答案1
得分: 0
在这里查看工作示例...
如果我们有一个将参数写入文件的脚本:
// 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 任务进行测试:
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 的:
gradle clean test -Pspring.profiles.active=TEST_PROFILE
英文:
Working example here ...
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")
}
}
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)
}
}
Note that parameters are passed to Gradle like so:
gradle clean test -Pspring.profiles.active=TEST_PROFILE
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论