通过 Spring 的 PropertyPlaceholderHelper 工具类替换占位符

该代码片段将介绍如何通过 Spring 的 PropertyPlaceholderHelper 工具类替换字符串中的占位符。

代码片段:

/**
 * 替换字符串中的 ${} 占位符
 * @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.

 

业精于勤,荒于嬉。——韩愈《进学解》
0 不喜欢
说说我的看法 -
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号