一直想解决这个问题,在网上扒了半天没找着,只能自己撸了,直接上代码
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/