com.github.hetianyi.common.util.ExpressionParserUtil Maven / Gradle / Ivy
package com.github.hetianyi.common.util;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* SpEL parser util.
*
* @author Jason He
* @version 1.0.6
* @since 1.0.5
* @date 2019-02-01
*/
public class ExpressionParserUtil {
/**
* expression parser.
*/
private static final ExpressionParser parser = new SpelExpressionParser();
/**
* expression cache map.
*/
private static final Map expressionMap = Collections.synchronizedMap(new HashMap<>());
/**
* get singleton expression.
* @param expression
* @return
*/
private static Expression getExpression(String expression) {
Expression ret = expressionMap.get(expression);
if (null == ret) {
synchronized (expressionMap) {
if (null == ret) {
ret = parser.parseExpression(expression);
expressionMap.put(expression, ret);
}
}
}
return ret;
}
/**
* parse SpEL expression using ExpressionParser with default settings.
* @param expression SpEL expression
* @param argKey variable name
* @param args variable value
* @param resultType result value type
* @param
* @return
*/
public static T parse(String expression, String argKey, Object[] args,
Class resultType) {
EvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable(argKey, args);
Expression exp = getExpression(expression);
return exp.getValue(ctx, resultType);
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy