All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lx.boot.lock.SpelParserUtils Maven / Gradle / Ivy

Go to download

使用文档: https://a7fi97h1rc.feishu.cn/docx/X3LRdtLhkoXQ8hxgXDQc2CLOnEg?from=from_copylink

There is a newer version: 1.1
Show newest version
package com.lx.boot.lock;

import com.lx.entity.Var;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Map;

//说明: el表达式解析
/** @author ylx 2022/12/2 14:36 */
public class SpelParserUtils {

    public static void main(String[]args){
        System.out.println(parse("#{#a}测试#{#a}",new Var("{a={b:'a'}}")));
    }

    public static String parse(String elString, JoinPoint point) {
        return parse(String.class, elString, point);
    }
    public static R parse(Class r, String elString, JoinPoint point) {
        //拼接解析springEl表达式的map
        String[] paramNames = ((MethodSignature) point.getSignature()).getParameterNames();
        Object[] args = point.getArgs();
        EvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < paramNames.length; i++) {
            context.setVariable(paramNames[i], args[i]);
        }
        return parse(r, elString,context);
    }

    public static String parse(String elString, Map map) {
        //通过evaluationContext.setVariable可以在上下文中设定变量。
        EvaluationContext context = new StandardEvaluationContext();
        map.forEach(context::setVariable);
        return parse(elString, context);
    }
    public static String parse(String elString, EvaluationContext context) {
        return parse(String.class, elString,context);
    }
    public static R parse(Class r, String elString, EvaluationContext context) {
        //创建表达式解析器
        SpelExpressionParser parser = new SpelExpressionParser();
        //解析表达式
        Expression expression = parser.parseExpression(elString, new TemplateParserContext());
        //使用Expression.getValue()获取表达式的值,这里传入了Evaluation上下文
        return expression.getValue(context ,r);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy