代码改变世界

配置文件中,字符串占位符替换

2019-08-14 11:34  话猫  阅读(718)  评论(0编辑  收藏  举报
      /**
	 * @description 动态list获取messages.properties中的校验信息
	 * @author chenhui
	 * @created_at 2019年8月13日 下午5:23:00
	 * @param key map
	 * @return
	 */
	public static void throwMessage(String key,List<String> list) {
		String value = getMessage(key);//getMessage方法是根据properties文件中的key 获得value
		for(int i = 0; i<list.size();i++) {
			value = value.replaceAll("\\{"+i+"\\}", list.get(i));
		}
		CstValidationException.newAndThrow(value);
	}
	
	/**
	 * @description 动态map获取messages.properties中的校验信息
	 * @author chenhui
	 * @created_at 2019年8月13日 下午5:23:00
	 * @param key
	 * @return
	 */
	public static void throwMessage(String key,Map<String, String> map) {
		String[] value =new String[1];//getMessage方法是根据properties文件中的key 获得value
		value[0] = getMessage(key);
		map.forEach((k,v)->{
			if(value[0].contains(k)) {
				value[0] = value[0].replaceAll("\\{"+k+"\\}", v);
			}
		});
		CstValidationException.newAndThrow(value[0]);
	}
//配置文件的写法:
key=这是{k}值
key=这{1}是{2}值

  思路:从message的properties文件中通过key取出value,将value中带有占位符得String字符串用正则表达式精确匹配,替换掉