import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.ParseException;
import org.springframework.expression.spel.SpelCompilerMode;
import org.springframework.expression.spel.SpelParserConfiguration;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import java.util.Objects;
/**
* SpEl工具类
*/
@Slf4j
public class SpElUtils {
/**
* 创建EL解析配置
*/
private static final SpelParserConfiguration CONFIGURATION = new SpelParserConfiguration(
SpelCompilerMode.IMMEDIATE, SpElUtils.class.getClassLoader());
/**
* 创建EL解析器
*/
private static final SpelExpressionParser PARSER = new SpelExpressionParser(CONFIGURATION);
/**
* 通过EL表达式获取对应的值
*
* @param source 数据源
* @param spEl EL表达式
* @param targetClass 目标类型的Class对象
* @param <T> 目标类型
* @return 获取到的值
*/
public static <T> T getValueBySpEl(Object source, String spEl, Class<T> targetClass) {
if (Objects.isNull(source) || StringUtils.isBlank(spEl)) {
return null;
}
try {
return PARSER.parseRaw(spEl).getValue(new StandardEvaluationContext(source), targetClass);
} catch (EvaluationException | ParseException e) {
log.info("EL表达式执行失败-source:{},spEl:{},targetClass:{},失败信息:{}", JSON.toJSONString(source),
spEl, targetClass, e.getMessage(), e);
}
return null;
}
/**
* 通过EL表达式获取对应的值
*
* @param source 数据源
* @param spEl EL表达式
* @return 获取到的值
*/
public static Object getValueBySpEl(Object source, String spEl) {
if (Objects.isNull(source) || StringUtils.isBlank(spEl)) {
return null;
}
try {
return PARSER.parseRaw(spEl).getValue(new StandardEvaluationContext(source));
} catch (EvaluationException | ParseException e) {
log.info("EL表达式执行失败-source:{},spEl:{},失败信息:{}", JSON.toJSONString(source), spEl,
e.getMessage(), e);
}
return null;
}
}
SpEl工具类
最新推荐文章于 2024-06-20 16:54:27 发布