我经常使用标准的Java属性文件来配置我的Groovy应用程序.我缺少的一个功能是能够将变量用作属性值的一部分,因此可以在使用期间动态扩展它们.我以为我可以使用以下设计提供此功能:
所以,如果我有一个属性文件config.properties,其属性如下:
version=2.3
local_lib=!!${env['GROOVY_HOME']}/${configProps.getProperty('version')}/lib!!
Run Code Online (Sandbox Code Playgroud)
该local_lib属性将从扩大GROOVY_HOME环境变量和版本属性值.
在我的应用程序中,我将其编码如下:
//Load the environment variables and configuration file
env=System.getenv()
configFile=new File('config.properties')
configProps= new Properties()
configProps.load(configFile.newDataInputStream())
//Replace configuration property values with their expanded equivalent
configProps.each{
//if a property value is a template we evaluate it
if (it.value.startsWith('!!')){
valTemplate=it.value.replace('!!','"')
it.value=evaluate(valTemplate)
}
}
//then we use the expanded property values
Run Code Online (Sandbox Code Playgroud)
这似乎有效.当我做
println configProps
Run Code Online (Sandbox Code Playgroud)
我看到该值被扩展而不是null
但是,展开属性的getProperty方法返回null.
assert configProps.getProperty('local_lib')=='C:\\DEVTOOLS\\groovy-2.4.7/2.3/lib'
| | |
| null false
[local_lib:C:\DEVTOOLS\groovy-2.4.7/2.3/lib, version:2.3] …Run Code Online (Sandbox Code Playgroud)