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

cn.crane4j.extension.spring.expression.SpelExpressionEvaluator Maven / Gradle / Ivy

There is a newer version: 2.8.2
Show newest version
package cn.crane4j.extension.spring.expression;

import cn.crane4j.core.support.expression.ExpressionContext;
import cn.crane4j.core.support.expression.ExpressionEvaluator;
import cn.crane4j.core.util.CollectionUtils;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.util.StringValueResolver;

import java.util.Map;
import java.util.Objects;

/**
 * {@link ExpressionEvaluator} implementation based on spring SpEL.
 *
 * @author huangchengxing
 */
@RequiredArgsConstructor
public class SpelExpressionEvaluator implements ExpressionEvaluator, DisposableBean, EmbeddedValueResolverAware {

    private final Map expressionCaches = CollectionUtils.newWeakConcurrentMap();
    private final ExpressionParser expressionParser;
    @Setter
    private StringValueResolver embeddedValueResolver;

    /**
     * Execute the expression in the specified above and return the execution result.
     *
     * @param expression expression
     * @param resultType result type
     * @param context context
     * @param  return type
     * @return result of execution
     */
    @Nullable
    @Override
    public  T execute(String expression, Class resultType, ExpressionContext context) {
        expression = Objects.isNull(embeddedValueResolver) ?
            expression : embeddedValueResolver.resolveStringValue(expression);
        EvaluationContext evaluationContext = (context instanceof SpelExpressionContext) ?
            (EvaluationContext)context : new SpelExpressionContext(context);
        return parseExpression(expression).getValue(evaluationContext, resultType);
    }

    /**
     * Clear resources when destroying the bean.
     */
    @Override
    public void destroy() {
        expressionCaches.clear();
    }

    private Expression parseExpression(String expression) {
        return CollectionUtils.computeIfAbsent(expressionCaches, expression, expressionParser::parseExpression);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy