[英]Using Groovy for variable expansion in Java properties
我經常使用標准的Java屬性文件來配置我的Groovy應用程序。 我一直缺少的一個功能是能夠將變量用作屬性值的一部分,因此它們可以在使用過程中動態擴展。 我以為我可以使用以下設計提供此功能:
所以,如果我有一個屬性文件config.properties ,其屬性如下:
version=2.3
local_lib=!!${env['GROOVY_HOME']}/${configProps.getProperty('version')}/lib!!
該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
這似乎有效。 當我做
println configProps
我看到該值被擴展而不是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]
造成這種差異的原因是什么? 我本來希望返回屬性映射中顯示的值。
您的local_lib
值看起來像一個String
,但它不是。 它是一個GString
,只是根據需要懶惰地強制轉換為String
(就像打印出configProps
映射值時一樣)。
因此, Properties.getProperty()
一個鮮為人知的效果在這里生效。 當實際映射值不是String時, Properties.getProperty()
返回null
。
因此,為了獲得所需的行為,在將值存儲在屬性映射中之前,需要將GString
強制轉換為String
。 像這樣:
it.value=evaluate(valTemplate).toString()
要么
it.value=evaluate(valTemplate) as String
然后你應該在下游看到所需的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.