1.Apache commons StringSubstitutor 替换占位符,用法介绍:
应用场景:
公司发送邮件短信,发送邮件,短信的内容通过模板配置,不同级别的人发送不同的内容。
发送邮件的内容:
例如:尊敬的${userName}${level};
public static void main(String[] args) {
User user = new User();
user.setName("张三");
user.setLevel("领导");
HashMap<String, String> map = new HashMap<>();
map.put("username", user.getName());
map.put("level",user.getLevel());
//配置的模板1
String content = "尊敬的${username}${level}上午好";
//配置的模板2
String content2 = "尊敬的${username}上午好";
System.out.println("模板1:"+new StrSubstitutor(map).replace(content));;
System.out.println("模板2:"+new StrSubstitutor(map).replace(content2));;
}
输出类容
模板1:尊敬的张三领导上午好
模板2:尊敬的张三上午好
StrSubstitutor在apache的commons-lang3包中,要使用,请在pom.xml里加入如下依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
1、直接替换系统属性值
String content2 = "java 版本= ${java.version} and 系统版本 = ${os.name}";
String sysProperties = StrSubstitutor.replaceSystemProperties(content2);
//1.直接替换系统属性值
System.out.println("直接替换系统属性值: "+sysProperties);
输出:直接替换系统属性值: java 版本= 1.8.0_291 and 系统版本 = Windows 10
2、使用Map替换字符串中的占位符
HashMap<String, String> map = new HashMap<>();
map.put("username", "张三");
map.put("level","领导");
//配置的模板1
String content = "尊敬的${username}${level}上午好";
System.out.println("模板1:"+new StrSubstitutor(map).replace(content));
输出:模板1:尊敬的张三领导上午好
3、StrSubstitutor会递归地替换变量,比如:
String content3 = "尊敬的${username}上午好";
HashMap<String, String> map3 = new HashMap<>();
map3.put("username", "${level}");
map3.put("level","领导");
System.out.println("模板3:"+new StrSubstitutor(map3).replace(content3));
输出:模板3:尊敬的领导上午好
4、有时变量内还嵌套其它变量,这个StrSubstitutor也是支持的,不过要调用下setEnableSubstitutionInVariables才可以。
String content4 = "尊敬的${username${level}}上午好";
Map<String, Object> params = Maps.newHashMap();
params.put("username2", "张三");
params.put("level", "2");
StrSubstitutor strSubstitutor = new StrSubstitutor(params);
strSubstitutor.setEnableSubstitutionInVariables(true);
System.out.println(strSubstitutor.replace(content4));
输出:尊敬的张三上午好