1

我有一个应用程序,其中有一个变量'file_Base_Path',我正在从 propertyFile(比如 sample.properties)读取它的值。我想将变量值设置为 user.home 并且 ${user.home}不起作用。如何将值设置为 user.home 以便它在 Linux 和 Windows 中都可以使用。

注意:我不能使用 System.getProperties('user.home') 因为值并不总是 user.home 它可能会有所不同

样本属性:

    file_Base_Path=${user.home}

我如何设置值:

  properties.getProperty("file_Base_Path")  //i'm expecting '/home/user' but it is returning '${user.home}'

谢谢

4

3 回答 3

0

如果您使用 Spring,@Value注释将${user.home}在注入时转换为适当的值。

保持 sample.properties 原样,并在您的班级中使用:

@Value("${file_Base_Path}")
private String filePath;

并且该${user.home}变量将在注入变量之前由 Spring 翻译。

有关更多信息,请参见价值

或者使用此处解释的 Apache Commons 配置

如果您不想使用 Spring 或 Apache Commons Configuration,那么您必须推出自己的解决方案,因为 Properties 和 System.getProperties 不会对属性文件的内容进行转换。你必须:

  1. 检查字符串是否包含“${”(对于用户指定完整路径的情况,如“C:/temp”,无需转换);
  2. 提取属性内容;
  3. 使用 System.getProperty(String) 获取实际值;
  4. 将值添加回找到它的位置的字符串(例如,在您有类似情况的情况下file_Base_Path=${user.home}/resources/${java.version})。
于 2015-04-30T15:33:13.823 回答
0

属性文件没有环境变量替换...

获取环境变量的方法是

System.getProperties("variablename");

如果它"variablename"本身是可变的,为什么不通过属性进行配置呢?

样本属性:

userhome.variable.name=user.home

Java代码:

String userhomeVariableName = properties.getProperty("userhome.variable.name");
String userhome = System.getProperties(userhomeVariableName);
于 2013-02-27T10:04:20.910 回答
0

你为什么不这样做:

 String localHome=properties.getProperty("file_Base_Path");
 if(localHome.equals("${user.home}"){
      localHome=System.getProperties("user.home");
 }
于 2013-02-27T10:05:17.940 回答