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

来源:互联网 发布:一起作业网刷学豆软件 编辑:程序博客网 时间:2024/06/08 17:10
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;}@Overridepublic 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}形式解析,




0 0
原创粉丝点击