Skip to content

Instantly share code, notes, and snippets.

@subchen
Last active January 3, 2016 20:38
Show Gist options
  • Save subchen/8516024 to your computer and use it in GitHub Desktop.
Save subchen/8516024 to your computer and use it in GitHub Desktop.
PlaceholderProperties.java
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PlaceholderProperties extends Properties {
private static final long serialVersionUID = 1L;
private static final Pattern PARAMETER_PATTERN = Pattern.compile("\\$\\{([^}]*)\\}");
public PlaceholderProperties() {
super();
}
public PlaceholderProperties(Properties properties) {
super(properties);
}
@Override
public String getProperty(String key) {
String value = super.getProperty(key);
return getRealValue(value);
}
@Override
public String getProperty(String key, String defaultValue) {
String value = super.getProperty(key);
return value == null ? defaultValue : getRealValue(value);
}
// 获取子属性
public Properties getProperties(String prefix) {
Properties props = new Properties();
prefix = prefix + '.';
for (Map.Entry<?, ?> entry : entrySet()) {
Object name = entry.getKey();
if (name instanceof String) {
String key = (String) name;
if (key.startsWith(prefix)) {
String value = this.getProperty(name);
if (value != null) {
key = key.substring(prefix.length());
props.put(key, value);
}
}
}
}
return props;
}
// 根据 System.getProperty() 替换变量
private String getRealValue(String value) {
if (value == null) {
return null;
}
if (value.indexOf('$') >= 0) {
Matcher matcher = PARAMETER_PATTERN.matcher(value);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String name = matcher.group(1);
String val = this.getProperty(name);
if (val == null) {
val = System.getProperty(name);
}
if (val == null) {
// 找不到变量值,保存原始文本不变
val = matcher.group();
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(val));
}
matcher.appendTail(sb);
value = sb.toString();
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment