Spring Expression Language (SpEL) 使用Map作為參數渲染模板字符串


代碼如下
package com.gsyn;


import org.springframework.expression.*;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author kstsixeam
 * @date 2021/1/6
 */
public class Main {

    public static void main(String[] args) throws Exception {
        new Main().test();
    }

    public void test() throws Exception {
        String template = "I have a pig, Its name is #{name}, It's #{age} years old";
        Expression expression = new SpelExpressionParser().parseExpression(template, ParserContext.TEMPLATE_EXPRESSION);
        HashMap<String, String> model = new HashMap<String, String>() {{
            put("name", "poi");
            put("age", "4");
        }};
        StandardEvaluationContext context = new StandardEvaluationContext(model);
        context.addPropertyAccessor(new MapPropertyAccessor());
        System.out.println(expression.getValue(context));
    }

    class MapPropertyAccessor implements PropertyAccessor {
        @Override
        public Class<?>[] getSpecificTargetClasses() {
            return new Class[]{Map.class};
        }

        @Override
        public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException {
            return (target instanceof Map && ((Map<?, ?>) target).containsKey(name));
        }

        @Override
        public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
            Assert.state(target instanceof Map, "參數不是Map類型");
            Map<?, ?> map = (Map<?, ?>) target;
            if (!map.containsKey(name)) {
                throw new AccessException("Map中未包含該key: " + name);
            }
            Object value = map.get(name);
            return new TypedValue(value);
        }

        @Override
        public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException {
            return false;
        }

        @Override
        public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException {

        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM