groovy为脚本评估提供上下文

groovy为脚本评估提供上下文,groovy,Groovy,这里我有简单的DSL application { name "Template application" } 原来我是这样用的 def application = new MainForm() application { name "Template application" } 其中,我在与DSL相同的文件中声明了application变量。(来自的对象main已重写方法调用) 现在我决定将我的DSL从同一个文件移到一些text文件中 // application.txt

这里我有简单的DSL

application {
    name "Template application"
}
原来我是这样用的

def application = new MainForm()
application {
    name "Template application"
}
其中,我在与DSL相同的文件中声明了
application
变量。(来自的对象
main已重写方法
调用

现在我决定将我的DSL从同一个文件移到一些
text
文件中

// application.txt
application {
    name "Template application"
}
我的主文件只有一行

evaluate(new File("application.txt"))
但如何为评估提供背景呢?因为现在它失败了,因为

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: application.application() is applicabe for argument types: (application$_run_closure1) values: [application$_run_closure1@5bfa9431]

作为一个解决方案,我喜欢这样做

def application = new MainForm()
Binding binding = new Binding()
binding.setVariable("application", application)

GroovyShell shell = new GroovyShell(binding)
    .evaluate(new File("application.txt"))

虽然我不确定是否可以做得更好

但我会这样做。在我看来,它100%正确。