使Java原生的Properties支持变量的嵌套引用

 

一直想解决这个问题,在网上扒了半天没找着,只能自己撸了,直接上代码


import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 对原生的Properties做了增强,以方便变量的嵌套引用
 * @author ZJ.Fun
 */
public class PropertiesEnhance extends Properties {

   @Override
  public String getProperty(String key) {
    String str = super.getProperty(key);

    String pattern = "\\$\\{.*?}";
    // 创建 Pattern 对象
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(str);

    while (m.find()) {
      String findKey = m.group();
      String fixKey = findKey.replaceAll("[${}]", "");
      String findValue = super.getProperty(fixKey);
      str = str.replaceAll(escapeExprSpecialWord(findKey), findValue);
    }
    return str;
  }

  /**
   * 转义正则特殊字符 ($()*+.[]?\^{},|)
   */
  public String escapeExprSpecialWord(String keyword) {
    if (keyword != null && keyword.length() > 0) {
      String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
      for (String key : fbsArr) {
        if (keyword.contains(key)) {
          keyword = keyword.replace(key, "\\" + key);
        }
      }
    }
    return keyword;
  }

}

 配置文件

project.name=lalalla
project.appsecret=156874
project.upload.url2=http://localhost:18000/${project.name}/${a.b.c}/${project.appsecret}/
a.b.c=13579

测试代码

  public static void main(String[] args) throws IOException {
    Properties prop = new PropertiesEnhance();
    prop.load(PropertiesEnhance.class.getClassLoader().getResourceAsStream("oss.properties"));
    System.out.println(prop.getProperty("project.upload.url2"));
  }

运行结果

http://localhost:18000/lalalla/13579/156874/

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值