Skip to content

Commit

Permalink
Merge pull request #650 from lilai23/optimize_properties
Browse files Browse the repository at this point in the history
【feature】优化.properties配置文件Map/List/Set数据格式配置
  • Loading branch information
robotLJW authored Aug 22, 2022
2 parents 1e29c2a + fbda180 commit a486616
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,22 @@ public class CommonConstant {
* 插件加载场景键
*/
public static final String PLUGIN_PROFILE = "profile";

/**
* 逗号
*/
public static final String COMMA = ",";

/**
* 点号
*/
public static final String DOT = ".";

/**
* 冒号
*/
public static final String COLON = ":";

private CommonConstant() {
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -172,9 +172,12 @@ private Object getConfig(Properties config, String key, Field field) {
*/
private String getConfigStr(Properties config, String key) {
Object arg = argsMap.get(key);
final String configVal;
String configVal;
if (arg == null) {
configVal = config.getProperty(key);
if (configVal == null) {
configVal = readMapOrCollection(configVal, config, key);
}
} else {
configVal = arg.toString();
}
Expand All @@ -187,6 +190,40 @@ public String getFixedValue(String key) {
});
}

/**
* 匹配Map/List/Set
* (1) 支持xxx.mapName.key1=value1配置Map
* (2) 支持xxx.xxx.listName[0]=elem1配置List或Set
*
* @param configVal 配置值
* @param config 配置
* @param key 配置键
* @return 配置值
*/
public String readMapOrCollection(String configVal, Properties config, String key) {
String result = configVal;
StringBuilder sb = new StringBuilder();
for (String propertyName : config.stringPropertyNames()) {
if (propertyName.startsWith(key)) {
// xxx.xxx.listName[0]=elem1 方式匹配List和Set
if (propertyName.matches("(.*)\\[[0-9]*]$")) {
sb.append(config.getProperty(propertyName))
.append(CommonConstant.COMMA);
} else {
// xxx.mapName.key1=value1 方式匹配Map
sb.append(propertyName.replace(key + CommonConstant.DOT, ""))
.append(CommonConstant.COLON)
.append(config.getProperty(propertyName))
.append(CommonConstant.COMMA);
}
}
}
if (sb.length() > 0) {
result = sb.deleteCharAt(sb.length() - 1).toString();
}
return result;
}

/**
* 类型转换,通过{@link ConfigValueUtil#toBaseType}等方法,将配置信息字符串进行类型转换
* <p>支持int、short、long、float、double、枚举、String和Object类型,以及他们构成的数组、List和Map
Expand Down

0 comments on commit a486616

Please sign in to comment.