配置文件或模板中的占位符替换工具类

import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 配置文件或模板中的占位符替换工具类
 */
public class PlaceholderUtils {

    private static final Logger logger = LoggerFactory.getLogger(PlaceholderUtils.class);

    /**
     * 占位前缀: "${"
     */
    public static final String PLACEHOLDER_PREFIX = "${";
    /**
     * 占位后缀: "}"
     */
    public static final String PLACEHOLDER_SUFFIX = "}";

    public static String resolvePlaceholders(String text, Map<String, String> parameter) {
        if (parameter == null || parameter.isEmpty()) {
            return text;
        }
        StringBuffer buf = new StringBuffer(text);
        int startIndex = buf.indexOf(PLACEHOLDER_PREFIX);//找到前缀“${”作为起始位置
        while (startIndex != -1) {//如果存在前缀“${”
            int endIndex = buf.indexOf(PLACEHOLDER_SUFFIX, startIndex + PLACEHOLDER_PREFIX.length());//确定对应后缀"}"的结束位置
            if (endIndex != -1) {//如果存在后缀"}"
                String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);//截取${}里面的key
                int nextIndex = endIndex + PLACEHOLDER_SUFFIX.length();//确定下一个查询的开始位置
                try {
                    String propVal = parameter.get(placeholder);//从map中获取key的值
                    if (propVal != null) {
                        buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);//通过map对应的值替代${}以及里面的值
                        nextIndex = startIndex + propVal.length();//确定替换后的下一个查询起始位置
                    } else {
                        logger.warn("parameter参数传递失败: '" + placeholder + "' in [" + text + "] ");
                    }
                } catch (Exception ex) {
                    logger.warn("占位解析异常: '" + placeholder + "' in [" + text + "]: " + ex);
                }
                startIndex = buf.indexOf(PLACEHOLDER_PREFIX, nextIndex);//将开始位置移动到替换后的查询位置
            } else {
                startIndex = -1;
            }
        }
        return buf.toString();//返回替换后的结果
    }
}
View Code

 

posted on 2019-08-29 09:21  龙猫大侠客  阅读(589)  评论(0编辑  收藏  举报

导航