SpringBoot引入SPEL模板字符串替換的兩種方式
Spring 表達(dá)式語言 (SpEL)
官方文檔:https://docs.spring.io/spring-framework/docs/6.0.x/reference/html/core.html#expressions
模板占位符 替換 {$name}
import org.springframework.context.expression.MapAccessor; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.util.PropertyPlaceholderHelper; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; /** * 內(nèi)容占位符 替換 * <p> * 模板占位符格式{$name} */ public class ContentHolderUtil { /** * 占位符前綴 */ private static final String PLACE_HOLDER_PREFIX = "{$"; /** * 占位符后綴 */ private static final String PLACE_HOLDER_SUFFIX = "}"; private static final StandardEvaluationContext EVALUATION_CONTEXT; private static final PropertyPlaceholderHelper PROPERTY_PLACEHOLDER_HELPER = new PropertyPlaceholderHelper( PLACE_HOLDER_PREFIX, PLACE_HOLDER_SUFFIX); static { EVALUATION_CONTEXT = new StandardEvaluationContext(); EVALUATION_CONTEXT.addPropertyAccessor(new MapAccessor()); } public static String replacePlaceHolder(final String template, final Map<String, String> paramMap) { String replacedPushContent = PROPERTY_PLACEHOLDER_HELPER.replacePlaceholders(template, new CustomPlaceholderResolver(template, paramMap)); return replacedPushContent; } private static class CustomPlaceholderResolver implements PropertyPlaceholderHelper.PlaceholderResolver { private final String template; private final Map<String, String> paramMap; public CustomPlaceholderResolver(String template, Map<String, String> paramMap) { super(); this.template = template; this.paramMap = paramMap; } @Override public String resolvePlaceholder(String placeholderName) { String value = paramMap.get(placeholderName); if (null == value) { String errorStr = MessageFormat.format("template:{0} require param:{1},but not exist! paramMap:{2}", template, placeholderName, paramMap.toString()); throw new IllegalArgumentException(errorStr); } return value; } } public static void main(String[] args) { Map<String,String> map = new HashMap<>(); map.put("name","張三"); map.put("age","12"); // 注意:{$}內(nèi)不能有空格 final String s = replacePlaceHolder("我叫 {$name}, 我今年 {$age} 歲了。", map); System.out.println(s); } }
common-text 方式:模板字符轉(zhuǎn)替換 ${}
添加依賴
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.10.0</version> </dependency> <!-- lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
測試
import lombok.extern.slf4j.Slf4j; import org.apache.commons.text.StringSubstitutor; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Slf4j public class CommonTextUtil { // 占位符前綴 private static final String prefix = "${"; // 占位符后綴 private static final String suffix = "}"; /* * commons-text * */ public static String replaceVar(Map<String, Object> vars, String template) { if (!StringUtils.hasLength(template)) { log.info(String.format("調(diào)用%s方法失敗,模板字符串替換失敗,模板字符串不能為空", Thread.currentThread().getStackTrace()[1].getMethodName())); return null; } if (CollectionUtils.isEmpty(vars)) { log.info(String.format("調(diào)用%s方法失敗,模板字符串替換失敗,map不能為空", Thread.currentThread().getStackTrace()[1].getMethodName())); return null; } List<String> tempStrs = vars.keySet().stream().map(s -> prefix + s + suffix). collect(Collectors.toList()); tempStrs.forEach(t -> { if (!template.contains(t)) { throw new RuntimeException(String.format("調(diào)用%s方法失敗,模板字符串替換失敗,map的key必須存在于模板字符串中", Thread.currentThread().getStackTrace()[1].getMethodName())); } }); StringSubstitutor stringSubstitutor = new StringSubstitutor(vars); return stringSubstitutor.replace(template); } public static void main(String[] args) { /* * 錯誤的場景:比如${變量},{}內(nèi)不能含有空格等等 * System.out.println(replaceVar(vals, "我叫${ name},今年${age }歲.")); * System.out.println(replaceVar(new HashMap<>(), temp)); * System.out.println(replaceVar(vals, "我叫張三")); * System.out.println(replaceVar(vals, "我叫${name},今年${age1}歲.")); * */ Map<String, Object> vals = new HashMap<>(); vals.put("name", "張三"); vals.put("age", "20"); String temp = "我叫${name},今年${age}歲."; System.out.println(replaceVar(vals, temp)); } }
到此這篇關(guān)于SpringBoot引入SPEL模板字符串替換的兩種方式的文章就介紹到這了,更多相關(guān)SpringBoot SPEL字符串替換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java如何根據(jù)不同系統(tǒng)動態(tài)獲取換行符和盤分割符
這篇文章主要介紹了Java如何根據(jù)不同系統(tǒng)動態(tài)獲取換行符和盤分割符,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12SpringCloud學(xué)習(xí)筆記之Feign遠(yuǎn)程調(diào)用
Feign是一個聲明式的http客戶端。其作用就是幫助我們優(yōu)雅的實現(xiàn)http請求的發(fā)送。本文將具體為大家介紹一下Feign的遠(yuǎn)程調(diào)用,感興趣的可以了解一下2021-12-12java進(jìn)制轉(zhuǎn)換工具類實現(xiàn)減少參數(shù)長度
這篇文章主要為大家介紹了java進(jìn)制轉(zhuǎn)換工具類實現(xiàn)減少參數(shù)長度示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02springboot后端接收前端傳數(shù)組參數(shù)三種方法
這篇文章主要給大家介紹了關(guān)于springboot后端接收前端傳數(shù)組參數(shù)三種方法,文中通過實例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2023-07-07SpringBoot中@PathVariable、@RequestParam和@RequestBody的區(qū)別和使用詳解
這篇文章主要介紹了SpringBoot中@PathVariable、@RequestParam和@RequestBody的區(qū)別和使用詳解,@PathVariable 映射 URL 綁定的占位符,通過@RequestMapping注解中的{}占位符來標(biāo)識URL中的變量部分,需要的朋友可以參考下2024-01-01