小编Ioa*_*sos的帖子

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

我经常使用标准的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)

java groovy variable-expansion properties-file

3
推荐指数
1
解决办法
957
查看次数