How to pass JVM arguments and script argument using GroovyShell?

耗尽温柔 提交于 2021-01-28 19:12:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!