【问题标题】:How to pass JVM arguments and script argument using GroovyShell?如何使用 GroovyShell 传递 JVM 参数和脚本参数?
【发布时间】:2021-01-13 00:20:45
【问题描述】:

所以我有一个 Groovy 脚本:

// TestScript.groovy
println args

然后在 Gradle 任务中我有

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 数组

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'))
}

【问题讨论】:

    标签: java spring-boot gradle groovy


    【解决方案1】:

    工作示例here ...

    如果我们有一个将参数写入文件的脚本:

    // 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
    

    【讨论】:

    • 谢谢!我喜欢你链接到一个可行的解决方案!现在的问题是运行它的脚本不运行测试用例。工作方式是 TestSuite 实际上有一个调用 @SpringBootTest 并整理结果的运行器。这里的问题是 TestSuite.groovy 现在找不到它的任何导入。我试图通过将类路径添加到 ClassLoader 来解决这个问题,但无济于事。如何让 GroovyShell 继承测试任务的类路径?
    • 我尝试了另一种方法,我有一个出色的question for here,它可能会提供对问题的更多见解。
    • @groovydude 我认为您的问题(回复:“现在的问题”)超出了原始问题的范围。请注意,第二条评论中的链接指向这个问题(!)。
    • @Michael Easter 你说得对。我已将问题标记为已接受。我将创建一个新问题。我希望你有一个关于如何添加正确的类路径的快速解决方案。我尝试使用 GroovyClassLoader,但没有奏效。
    猜你喜欢
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2015-02-25
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    相关资源
    最近更新 更多