如何在用户定义的.properties文件中引用系统属性?

我想为我的生产.properties文件定义工作目录的属性(比如work.dir=/home/username/working-directory ),而不用硬编码/home/username

我想在硬编码/home/username上引用系统属性user.home ,以使work.dir更通用。

如何引用系统属性并将其连接到用户定义的.properties中的其他用户定义的字符串?

注意:我不想访问我的java代码中的user.home属性,而是访问我定义的.properties。 我希望能够将生产和开发的不同值替换为work.dir值(例如JUnit测试)。

从文件中获取属性,然后替换支持的宏。

 String propertyValue = System.getProperty("work.dir"); String userHome = System.getProperty("user.home" ); String evaluatedPropertyValue = propertyValue.replace("$user.home", userHome ); 

您可以使用Commons Configuration管理属性并使用Variable Interpolation

如果您熟悉Ant或Maven,那么您肯定已经遇到了在加载配置文件时自动扩展的变量(如${token} )。 Commons Configuration也支持此function[…]

这将允许.properties文件

 work.dir=${user.home}/working-directory 

java.util.Properties中没有此function。 但是许多库为属性添加了变量替换

以下是使用OWNER API库尝试执行的操作示例(请参阅“导入属性”一节):

 public interface SystemPropertiesExample extends Config { @DefaultValue("Welcome: ${user.name}") String welcomeString(); @DefaultValue("${TMPDIR}/tempFile.tmp") File tempFile(); } SystemPropertiesExample conf = ConfigFactory.create(SystemPropertiesExample.class, System.getProperties(), System.getenv()); String welcome = conf.welcomeString(); File temp = conf.tempFile();