问题
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:
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
来源:https://stackoverflow.com/questions/64084870/how-to-pass-jvm-arguments-and-script-argument-using-groovyshell