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

com.feingto.cloud.config.redis.support.SpELContext Maven / Gradle / Ivy

The newest version!
package com.feingto.cloud.config.redis.support;

import com.feingto.cloud.kit.ClassKit;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionException;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * EL 表达式上下文
 *
 * @author longfei
 */
@Slf4j
public class SpELContext {
    private static final ThreadLocal LOCAL_CONTEXT = new ThreadLocal<>();
    private static final ExpressionParser PARSER = new SpelExpressionParser();

    private static void putContext(EvaluationContext context) {
        LOCAL_CONTEXT.set(context);
    }

    public static EvaluationContext getContext() {
        return LOCAL_CONTEXT.get();
    }

    public static void removeContext() {
        LOCAL_CONTEXT.remove();
    }

    public static void putContext(Class clazz, Method method, Object[] args) throws Throwable {
        Map params = ClassKit.getFieldMap(clazz, method.getDeclaringClass().getName(), method.getName(), args);
        EvaluationContext context = new StandardEvaluationContext();
        for (String key : params.keySet()) {
            context.setVariable(key, params.get(key));
        }
        putContext(context);
    }

    public static void putContext(Class clazz, JoinPoint jp) throws Throwable {
        String classType = jp.getTarget().getClass().getName();
        Class clz = Class.forName(classType);
        Map params = ClassKit.getFieldMap(clazz, clz.getName(), jp.getSignature().getName(), jp.getArgs());
        EvaluationContext context = new StandardEvaluationContext();
        for (String key : params.keySet()) {
            context.setVariable(key, params.get(key));
        }
        putContext(context);
    }

    /**
     * 解析EL表达式
     */
    public static String parserEl(String el) {
        try {
            Expression exp = PARSER.parseExpression(el);
            String key = exp.getValue(getContext(), String.class);
            log.trace("SpEL: {} >>> {}", el, key);
            return key;
        } catch (ExpressionException e) {
            log.warn("SpEL expression[{}] parser failed: {}", el, e.getMessage());
            return el;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy