使用Groovy在Java属性中进行变量扩展

Ioa*_*sos 3 java groovy variable-expansion properties-file

我经常使用标准的Java属性文件来配置我的Groovy应用程序.我缺少的一个功能是能够将变量用作属性值的一部分,因此可以在使用期间动态扩展它们.我以为我可以使用以下设计提供此功能:

  1. 使用特殊格式注释应扩展的属性.我选择将这些模板包含在双惊叹号(!!)中.这些属性值本质上是一个用局部变量扩展的模板
  2. 在使用应用程序中的属性之前,使用groovy'alcome'方法在模板中展开应用程序变量
  3. 使用前将原始属性键重新分配给新值

所以,如果我有一个属性文件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)

造成这种差异的原因是什么?我本来希望返回属性映射中显示的值.

Bal*_*Rog 5

你的local_lib价值看起来像是String,但事实并非如此.这是一个GString,只是String根据需要懒散地强制(就像打印出configProps地图值时).

因此,一个鲜为人知的Properties.getProperty()效果在这里起作用.当实际的映射值不是String时,Properties.getProperty()返回null.

因此,为了获得所需的行为,您需要在将值存储在属性映射中之前强制转换为GStringto String.像这样:

it.value=evaluate(valTemplate).toString()
Run Code Online (Sandbox Code Playgroud)

要么

it.value=evaluate(valTemplate) as String
Run Code Online (Sandbox Code Playgroud)

然后你应该在下游看到所需的结果.