spring中StrSubstitutor更换表达式符号和忽略大小写StrLookup

StrSubstitutor是一个很特殊的类,它使用${}的方法在形成了一个可配置的模板String。首先可以用一个Map声明一个 StrSubstitutor,然后使用replace方法,把模板String中使用${}的部分(内部为Map的key),转化为Map中的值,由此 做到动态更改字符串内容的效果。例如:
 
Map valuesMap = new HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

resolvedString即为替换参数后的字符串内容。
输出结果为:The quick brown fox jumped over the lazy dog.


但是我们需求需要key可以忽略大小写,下面这样就可以了
	       Map<String, String> valuesMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);	
	       valuesMap.put("animal", "quick brown fox");
			valuesMap.put("target", "lazy dog");
			String templateString = "The ${Animal} jumped over the ${target}.";
//			String templateString = "The &{animal} jumped over the &{target}.";
			
			StrSubstitutor sub = new StrSubstitutor(valuesMap);
//			StrSubstitutor sub = new StrSubstitutor(valuesMap, "&(", ")");
			String resolvedString = sub.replace(templateString);
			System.out.println("the str="+resolvedString);	

但是我们是用hashmap的,另外我们表达式不是${Animal}这种,是#{Animal},所以需要改写,

定义一个CaseInsensitiveStrLookup类

public class CaseInsensitiveStrLookup<V> extends StrLookup<V> {

private final Map<String, V> map;

CaseInsensitiveStrLookup(final Map<String, V> map) {
    this.map = map;
}

@Override
public String lookup(final String key) {
    String lowercaseKey = key.toLowerCase(); //lowercase the key you're looking for
    if (map == null) {
        return null;
    }
    final Object obj = map.get(lowercaseKey);
    if (obj == null) {
        return null;
    }
    return obj.toString();
}
}

然后测试

		 Map<String, String> messageValues = new HashMap<String, String>();
		    messageValues.put("killer", "张三");
		    messageValues.put("target", "李四");
//		    StrSubstitutor sub = new StrSubstitutor(new CaseInsensitiveStrLookup<String>(messageValues), "&(", ")", '\\');
		    StrSubstitutor sub = new StrSubstitutor(new CaseInsensitiveStrLookup<String>(messageValues), "#(", ")", '\\');

//		    String format2 = sub.replace("Information: &(killer) killed &(target)!");
		    String format2 = sub.replace("Information: #(killer) killed #(target)!");
		    System.out.println("the str="+format2);	
//		    String format = sub.replace("Information: &(KILLER) killed &(TARGET)!");
		    String format = sub.replace("Information: #(KILLEr) killed #(TARGET)!");
		    System.out.println("the str="+format);	


哦了,key的大小写忽略,使用#{Animal}形式解析,




发布了242 篇原创文章 · 获赞 114 · 访问量 185万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览