如何使用Spring Expression Language

时间:2017-04-24 04:38:38

标签: java spring spring-el

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

是否可以删除符号@#

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

1 个答案:

答案 0 :(得分:2)

我不确定你的动机是什么; 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);
相关问题