字符串占位符替换工具类——Apache StringSubstitutor

1 背景

众所周知Java中的字符串占位符替换非常不友好,无论是String#format还是MessageFormat#format都只能说能用,但说不上好用,关于以上两种字符串格式化的用法请参考:Java String formatMessageFormat format,本文推荐org.apache.commons.text.StringSubstitutor,StrSubstitutor是一个工具类,它的目的也是字符替换,它封装复杂的替换方法,并且可以实现递归替换、提供默认值、自定义占位符等。

2 使用

首先导入依赖maven坐标如下:

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

StrSubstitutor的封装了很多实用强大的功能,本文只介绍简单的使用。

2.1 使用系统属性

StringSubstitutor.replaceSystemProperties("You are running with java.version = ${java.version} and os.name = ${os.name}.");

2.2 使用map

下面用我司实际项目代码展示:

public CommonResponse<NotificationInstance> render(CommonRequest<NotificationInstanceDto> request) {
         try {
         // 获取请求参数
             NotificationInstanceDto requestParams = request.getRequestParams();
             // 获取模板字符串(含有占位符)
             String contentTemplate = requestParams.getContentTemplate();
             // 具体的业务数据,需要替换占位符
             Map<String, String> dataMap = requestParams.getBizData();
             // 创建StringSubstitutor,入参是要替换的业务数据map
             StringSubstitutor sub = new StringSubstitutor(dataMap);
             // 占位符字段替换为具体业务数据,入参为模板字符串
             String resolvedString = sub.replace(contentTemplate);
             NotificationInstance instance = new NotificationInstance();
             BeanUtils.copyProperties(requestParams, instance);
             instance.setNotificationContent(resolvedString);
             return this.success(instance);
         } catch (Exception e) {
             LogUtil.error(e);
             BizError error = new TemplateRenderError(null);
             error.setErrorMessage(e.getMessage());
             return this.fail(error);
         }
    }

注意,替换占位符的map中key要与占位符名相同,例如:

<html>${accountName},您好<br>
【${tenantName}】 系统管理员为您开通了账号,登录信息为:<br>
登录帐号为:${accountNo}<br>
初始密码为:${password}<br>
为了保障您的账号安全,请使用该密码登录xxx系统后及时修改密码,谢谢。</html>

此时dataMap中代码应类似为:

dataMap.put("tenantName", "xxx");
dataMap.put("accountNo", "admin");
dataMap.put("password", "skull1Qx");

最终结果为:

image-20240411114713996

2.3 自定义占位符

查看源码可以发现默认占位符为${},进一步查看构造方法可以发现:

public <V> StringSubstitutor(Map<String, V> valueMap, String prefix, String suffix, char escape) {
     this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, escape);
}

image-20240411113105933

其中入参prefix代表前缀,suffix代表后缀,escape表示要排除的字符,所以比如想要以%{}作为占位符可以这么创建:

StrSubstitutor sub = new StrSubstitutor(valuesMap, "%{", "}", '%');

更多详细使用请参考官方文档:

https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html


本博客内容仅供个人学习使用,禁止用于商业用途。转载需注明出处并链接至原文。

posted @ 2024-04-12 16:36  爱吃麦辣鸡翅  阅读(62)  评论(0编辑  收藏  举报