欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2024年03月06日 11:12:44   作者:師小師  
在 Spring Boot 中,我們可以使用字符串替換工具類來實現(xiàn)這些功能,本文主要介紹了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)文章

最新評論