使用Apache commons-text进行占位符替换

Apache commons-lang3包中的 StrSubstitutor可以将字符串中的变量替换为指定的值

从commons-lang3-3.6.jar版本起 org.apache.commons.lang3.text.StrSubstitutor已经过时,文档上建议用commons-text的org.apache.commons.text.StrSubstitutor代替。

先引入

 			<dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-text</artifactId>
                <version>1.9</version>
            </dependency>

写个简单的方法测试一下

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.text.StrSubstitutor;
/**
 * 占位符替换
 *
 */
public class Placeholder {
    /**
     * 替换
     * @param source 源内容
     * @param parameter 占位符参数
     * @param prefix 占位符前缀 例如:${
     * @param suffix 占位符后缀 例如:}
     * @param enableSubstitutionInVariables 是否在变量名称中进行替换 例如:${system-${版本}}
     * 
     * 转义符默认为'$'。如果这个字符放在一个变量引用之前,这个引用将被忽略,不会被替换 如$${a}将直接输出${a}
     * @return
     */
    public static String replace(String source,Map<String, Object> parameter,String prefix, String suffix,boolean enableSubstitutionInVariables){
        //StrSubstitutor不是线程安全的类
        StrSubstitutor strSubstitutor = new StrSubstitutor(parameter,prefix, suffix);
        //是否在变量名称中进行替换
        strSubstitutor.setEnableSubstitutionInVariables(enableSubstitutionInVariables);
        return strSubstitutor.replace(source);
    }
    
    /**
     * 测试
     */
    public static void test(){
       //替换字符串中的占位符
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user", "admin");
        params.put("password", "123456");
        params.put("system-version", "windows 10");
        params.put("版本", "version");//中文也可以
        params.put("详", "翔");//中文也可以

        System.out.println(replace("你的用户名是${user},密码是${password}。系统版本${system-${版本}}",params,"${","}",true));
        System.out.println(replace("表达对一个人无比的崇拜怎么表述最好?答:“愿闻其${详}”",params,"${","}",false));
    }
    
}

运行结果

你的用户名是admin,密码是123456。系统版本windows 10
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值