如何使用 Spring 表达式语言自定义 bean 表达式的编程评估

How to customize the programmatically evaluation of a bean expression with Spring Expression Language

我正在尝试以编程方式使用 SpEL 计算表达式。 我可以评估以下表达式。 @expressionUtil.substractDates(#fromDate,#toDate)

是否可以删除符号 @#

所以新表达式将像 expressionUtil.substractDates(fromDate,toDate)..

我不确定你的动机是什么; fromDatetoDate是变量,由#表示,@表示需要咨询bean解析器。

都是求值的根对象。你可以用一个简单的javabean作为包装器做你想做的事...

final ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression("expressionUtil.subtractDates(fromDate, toDate)");
Wrapper wrapper = new Wrapper();
wrapper.setFromDate(new Date(System.currentTimeMillis()));
wrapper.setToDate(new Date(System.currentTimeMillis() + 1000));
Long value = expression.getValue(wrapper, Long.class);
System.out.println(value);

...

public static class Wrapper {

    private final ExpressionUtil expressionUtil = new ExpressionUtil();

    private Date fromDate;

    private Date toDate;

    public Date getFromDate() {
        return this.fromDate;
    }

    public void setFromDate(Date fromDate) {
        this.fromDate = fromDate;
    }

    public Date getToDate() {
        return this.toDate;
    }

    public void setToDate(Date toDate) {
        this.toDate = toDate;
    }

    public ExpressionUtil getExpressionUtil() {
        return this.expressionUtil;
    }

}

public static class ExpressionUtil {

    public long subtractDates(Date from, Date to) {
        return to.getTime() - from.getTime();
    }

}

或者您甚至可以使用 Map,但在那种情况下,您必须将 MapAccessor 添加到评估上下文中,因为默认情况下它没有。 .

final ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.addPropertyAccessor(new MapAccessor());
Expression expression = parser.parseExpression("expressionUtil.subtractDates(fromDate, toDate)");
Map<String, Object> map = new HashMap<>();
map.put("expressionUtil", new ExpressionUtil());
map.put("fromDate", new Date(System.currentTimeMillis()));
map.put("toDate", new Date(System.currentTimeMillis() + 1000));
Long value = expression.getValue(context, map, Long.class);
System.out.println(value);