代码片段:
/**
* 替换字符串中的 ${} 占位符
* @param message 消息字符串
* @param map 替换占位符的数据
* @return 替换后的字符串
*/
public static String replacePlaceholderValue(String message, Map<String, String> map){
if(!StringUtils.hasText(message)){
return message;
}
//定义${开头 ,}结尾的占位符
PropertyPlaceholderHelper propertyPlaceholderHelper = new PropertyPlaceholderHelper("${", "}");
//调用替换
return propertyPlaceholderHelper.replacePlaceholders(message, map::get);
}测试代码:
public static void main(String[] args) {
String message = "Hi ${name}, your score is ${score}.";
Map<String, String> map = new HashMap<String,String>(){
{
put("name", "Tom");
put("score", "210");
}
};
System.out.println(replacePlaceholderValue(message, map));
}运行输出信息如下:
Hi Tom, your score is 210.