[英]use a seperate data file to read variables in groovy
I am trying to separate variables data from my actual script groovy file. 我正在尝试从实际的脚本常规文件中分离变量数据。
def test = [a,b,c]
def test2 = ['foo': [a,x,y], 'bar': [q,w,e]]
def function(String var){}
def function2 {
test.each
{
item ->
print test
}
}
since my values in the variables are changing constantly but not the script. 因为变量中的值在不断变化,但脚本在变化。 How do I make my groovy read a variable file and load it during the runtime? 如何使Groovy读取变量文件并在运行时加载它?
I want it to look something like this maybe. 我希望它看起来像这样。
variables.properties
def test = [a,b,c]
def test2 = ['foo': [a,x,y], 'bar': [q,w,e]]
main.groovy 主沟
load ( variable.properties)
def function(String var){}
def function2 {
test.each
{
item ->
print test
}
}
In Groovy, it is possible to evaluate data as Groovy code. 在Groovy中,可以将数据评估为Groovy代码。 This is a powerful technique. 这是一项强大的技术。 It is arguably a bit much for your goals, but would work. 可以说这对您的目标有很多帮助,但可以。
Consider this config.data
file (it is a Groovy file but can be named anything): 考虑以下config.data
文件(它是一个Groovy文件,但可以命名为任何文件):
test = ['a','b','c']
test2 = ['foo': ['a','x','y'], 'bar': ['q','w','e']]
and the App.groovy
file. 和App.groovy
文件。 It sets up a Binding
of variables in a GroovyShell
. 它在GroovyShell
设置变量的Binding
。 The Config
is evaluated inside the shell, and we can reference the variables in the main app. Config
在外壳内部进行评估,我们可以在主应用程序中引用变量。
def varMap = [:]
varMap["test"] = []
varMap["test2"] = [:]
def binding = new Binding(varMap)
def shell = new GroovyShell(binding)
def function2 = { test, test2 ->
test.each { println "test item: ${it}" }
test2.each { println "test2 item: ${it}" }
}
// ------ main
// load Config and evaluate it
def configText = new File(args[0]).getText()
shell.evaluate(configText)
def test = varMap["test"]
def test2 = varMap["test2"]
function2(test, test2)
an example usage: 用法示例:
$ groovy App.groovy config.data
test item: a
test item: b
test item: c
test2 item: foo=[a, x, y]
test2 item: bar=[q, w, e]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.