使用属性文件中的属性

我为标题道歉..我找不到更好的方式来解释这种情况。

我使用Property类加载属性文件,如URL http://www.exampledepot.com/egs/java.util/Props.html中所述

我的问题是我可以在该属性文件中使用属性吗?

例:

test.properties

url.main="http://mysite.com" url.games={url.main}/games url.images={url.main}/images . . . 

是否可以使用其他语法?

谢谢

之前从未见过。 你当然可以制作自己的预处理器。 只要引用的属性在对它的任何引用之前发生,您应该能够使用一些正则表达式/字符串替换来实现它。 但是:我不推荐这种方法。

通过定义不同的属性更好地解决重复问题:

  1. url.games={url.main}/games更改为url.games_extension=/games
  2. prepend: url.mainurl.games_extension以获取应用程序代码中的完整游戏URL。

Apache Commons Configuration提供了这个: http : //commons.apache.org/configuration/

用于加载配置文件的简单示例代码:

 Configuration config = new PropertiesConfiguration("config.properties"); 

您可以使用’变量插值’属性,如此处所述http://commons.apache.org/configuration/userguide/howto_basicfeatures.html#Variable_Interpolation

 application.name = Killer App application.version = 1.6.2 application.title = ${application.name} ${application.version} 

它还允许您在使用时包含其他配置文件:

 include = colors.properties include = sizes.properties 

除了一系列其他function。

我编写了自己的配置库,它支持属性文件中的变量扩展, 看看它是否提供了你需要的东西。 我写的一篇文章介绍了这个function。

没有直接的方法来替换属性文件/对象中的属性值,但是一旦通过getProperty()方法读取,就可以替换属性值。 要生成连接消息 – 请查看MessageFormat类。

 String baseValue=prop.getProperty("url.main"); 

我已经完成了类似的事情并没有那么困难,你只需inheritanceProperties类并实现自己的getProperty方法,检查模式并在必要时替换它。

 //this makes the pattern ${sometext} static public final String JAVA_CONFIG_VARIABLE = "\\$\\{(.*)\\}"; @Override public String getProperty(String key) { String val = super.getProperty(key); if( val != null && val.indexOf("${") != -1 ) { //we have at least one replacable parm, let's replace it val = replaceParms(val); } return val; } public final String replaceParms(String in) { if(in == null) return null; //this could be precompiled as Pattern is supposed to be thread safe Pattern pattern = Pattern.compile(JAVA_CONFIG_VARIABLE); Matcher matcher = pattern.matcher(in); StringBuffer buf = new StringBuffer(); while (matcher.find()) { String replaceStr = matcher.group(1); String prop = getProperty(replaceStr); //if it isn't in our properties file, check if it is a system property if (prop == null ) prop = System.getProperty(replaceStr); if( prop == null ) { System.out.printf("Failed to find property '%s' for '%s'\n", replaceStr, in); } else { matcher.appendReplacement(buf, prop); } } matcher.appendTail(buf); String result = buf.toString(); return result; }