Java占位符总结

实现方式

java开发中,各种文本快速替换总结

方式一: jdk1.8–java.text.MessageFormat

    String text = MessageFormat.format("用户:{0}您好,短信验证码为:{1}", "张三", "10086");

方式二: Log4j–javaorg.slf4j.helpers.MessageFormatter

    /**
     * render placeholder string like log format, e.g. {@code Messages#format("Hello {}","World!")}
     *
     * @param messagePattern message pattern use {} as placeholder
     * @param params         placeholder value
     * @return formatted string
     */
    public static String format(String messagePattern, Object... params) {
        return params == null ? messagePattern : MessageFormatter.arrayFormat(messagePattern, params).getMessage();
    }

方式三: commons-text–org.apache.commons.text.StringSubstitutor

  • maven
     <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-text</artifactId>
         <version>1.9</version>
     </dependency>
  • 使用

    Map<String, Object> contextMap = new HashMap<>();
    contextMap.put("name", "张三);

    String template = "hello ${name}";
    StringSubstitutor stringSubstitutor = new StringSubstitutor(contextMap);
    String navigationJson = stringSubstitutor.replace(template);

方式四: hutool工具类实现

  • hutool的实现和用法和Log4j类似
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.6.3</version>
    </dependency>
  • 使用
CharSequenceUtil.format("用户:[{}] 注销session:[{}]", "张三", "10086");

代码示例

测试

package com.myron;

import org.apache.commons.text.StringSubstitutor;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.MessageFormatter;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 不同占位符方案使用实例
 */
public class PlaceholderTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(PlaceholderTest.class);
    public static void main(String[] args) {
 
        // 短信模板
        String template = "#userName#您好,欢迎使用#system#,您的验证码是:#code#,若非本人操作,请忽略!";
 
        // 占位符对应的值
        Map<String,String> valueMap = new HashMap<>();
        valueMap.put("userName","阿杰");
        valueMap.put("system","查询系统");
        valueMap.put("code","666666");
 
        StringSubstitutor sub = new StringSubstitutor();
 
        // 使用静态方法传入自定义的占位符前后缀
        String replace = sub.replace(template,valueMap,"#","#");
 
        System.out.println(replace); // 阿杰您好,欢迎使用查询系统,您的验证码是:666666,若非本人操作,请忽略!
 
    }


    @Test
    public void testMessageFormat() {
        LOGGER.info("MessageFormat.format {0}占位符------------开始");
        String text = MessageFormat.format("用户:{0}您好,短信验证码为:{1}", "张三", "10086");
        LOGGER.info(text);
        LOGGER.info("MessageFormat.format {0}占位符------------结束");
    }

    @Test
    public void testMessageFormatter() {
        LOGGER.info("MessageFormatter.arrayFormat {}占位符------------开始");
        String text = MessageFormatter.arrayFormat("用户:{}您好,短信验证码为::{}", new String[]{"张三", "10086"}).getMessage();
        LOGGER.info(text);
        LOGGER.info("MessageFormatter.arrayFormat {}占位符------------结束");
    }

    /**
     <dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-text</artifactId>
     <version>1.9</version>
     </dependency>
     */
    @Test
    public void testStringSubstitutor() {
        LOGGER.info("StringSubstitutor.replace ${}占位符------------开始");

        Map<String, Object> contextMap = new HashMap<>();
        contextMap.put("name", "张三");
        contextMap.put("code", "10086");

        String template = "用户:${name}您好,短信验证码为:${code}";
        StringSubstitutor stringSubstitutor = new StringSubstitutor(contextMap);
        String text = stringSubstitutor.replace(template);
        LOGGER.info(text);
        LOGGER.info("StringSubstitutor.replace ${}占位符------------结束");
    }

    /**
     * render placeholder string like log format, e.g. {@code Messages#format("Hello {}","World!")}
     *
     * @param messagePattern message pattern use {} as placeholder
     * @param params         placeholder value
     * @return formatted string
     */
    public static String format(String messagePattern, Object... params) {
        return params == null ? messagePattern : MessageFormatter.arrayFormat(messagePattern, params).getMessage();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值