最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot引入SPEL模板字符串替換的兩種方式

 更新時(shí)間:2024年03月06日 11:12:44   作者:師小師  
在 Spring Boot 中,我們可以使用字符串替換工具類來(lái)實(shí)現(xiàn)這些功能,本文主要介紹了SpringBoot引入SPEL模板字符串替換的兩種方式,具有一定的參考價(jià)值,感興趣的可以了解一下

Spring 表達(dá)式語(yǔ)言 (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>

測(cè)試

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) {
        /*
         * 錯(cuò)誤的場(chǎng)景:比如${變量},{}內(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

 

相關(guān)文章

  • spring-cloud入門(mén)之eureka-server(服務(wù)發(fā)現(xiàn))

    spring-cloud入門(mén)之eureka-server(服務(wù)發(fā)現(xiàn))

    本篇文章主要介紹了spring-cloud入門(mén)之eureka-server(服務(wù)發(fā)現(xiàn)),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-01-01
  • Java讀取項(xiàng)目json文件并轉(zhuǎn)為JSON對(duì)象的操作

    Java讀取項(xiàng)目json文件并轉(zhuǎn)為JSON對(duì)象的操作

    這篇文章主要介紹了Java讀取項(xiàng)目json文件并轉(zhuǎn)為JSON對(duì)象的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • SpringBoot開(kāi)發(fā)實(shí)戰(zhàn)之自動(dòng)配置

    SpringBoot開(kāi)發(fā)實(shí)戰(zhàn)之自動(dòng)配置

    SpringBoot的核心就是自動(dòng)配置,自動(dòng)配置又是基于條件判斷來(lái)配置Bean,下面這篇文章主要給大家介紹了關(guān)于SpringBoot開(kāi)發(fā)實(shí)戰(zhàn)之自動(dòng)配置的相關(guān)資料,需要的朋友可以參考下
    2021-08-08
  • spring 定時(shí)任務(wù)@Scheduled詳解

    spring 定時(shí)任務(wù)@Scheduled詳解

    這篇文章主要介紹了spring 定時(shí)任務(wù)@Scheduled的相關(guān)資料,文中通過(guò)示例代碼介紹的很詳細(xì),相信對(duì)大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值,有需要的朋友們下面來(lái)一起看看吧。
    2017-01-01
  • java驗(yàn)證碼生成具體代碼

    java驗(yàn)證碼生成具體代碼

    這篇文章主要為大家分享了java驗(yàn)證碼生成具體代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-04-04
  • 淺談Redis持久化的幾種方式

    淺談Redis持久化的幾種方式

    這篇文章主要介紹了淺談Redis持久化的幾種方式,前面說(shuō)到了Redis持久化的 實(shí)現(xiàn)方式主要分為了:快照持久化(RDB)、寫(xiě)日志持久化(AOF)
    ,其中快照持久化方式也就是RDB ,需要的朋友可以參考下
    2023-08-08
  • SpringBoot 整合 JMSTemplate的示例代碼

    SpringBoot 整合 JMSTemplate的示例代碼

    這篇文章主要介紹了SpringBoot 整合 JMSTemplate的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Spring?Boot中的max-http-header-size配置方式

    Spring?Boot中的max-http-header-size配置方式

    這篇文章主要介紹了Spring?Boot中的max-http-header-size配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • Gson之toJson和fromJson方法的具體使用

    Gson之toJson和fromJson方法的具體使用

    Gson是Google的一個(gè)開(kāi)源項(xiàng)目,可以將Java對(duì)象轉(zhuǎn)換成JSON,也可能將JSON轉(zhuǎn)換成Java對(duì)象。本文就詳細(xì)的介紹了toJson和fromJson方法的具體使用,感興趣的可以了解一下
    2021-11-11
  • Java獲取客戶端真實(shí)IP地址經(jīng)典寫(xiě)法與Lambda寫(xiě)法對(duì)比示例代碼

    Java獲取客戶端真實(shí)IP地址經(jīng)典寫(xiě)法與Lambda寫(xiě)法對(duì)比示例代碼

    在網(wǎng)絡(luò)編程中,獲取客戶端的IP地址和端口地址是非常常見(jiàn)的需求,這篇文章主要介紹了Java獲取客戶端真實(shí)IP地址經(jīng)典寫(xiě)法與Lambda寫(xiě)法對(duì)比的相關(guān)資料,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2026-05-05

最新評(píng)論

南宁市| 富平县| 孝昌县| 上思县| 巧家县| 鹤山市| 湘潭县| 东源县| 即墨市| 河间市| 永善县| 杂多县| 平乡县| 伊宁县| 米泉市| 安仁县| 襄汾县| 奈曼旗| 黄龙县| 英德市| 双桥区| 青龙| 慈溪市| 天门市| 铜山县| 肃宁县| 同德县| 渭源县| 金寨县| 平湖市| 应城市| 长治市| 清水县| 通江县| 长垣县| 建水县| 措美县| 长春市| 武清区| 甘孜| 沾化县|