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