代码如下
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 {
}
}
}