我試圖以編程方式使用SpEL來評估表達式。 我可以評估下面的表達式。 @expressionUtil.substractDates(#fromDate,#toDate)
如何以編程方式自定義使用Spring表達式語言評估bean表達式
是否可以刪除符號@
和#
?
所以新的表達會像expressionUtil.substractDates(fromDate,toDate)
..
我試圖以編程方式使用SpEL來評估表達式。 我可以評估下面的表達式。 @expressionUtil.substractDates(#fromDate,#toDate)
如何以編程方式自定義使用Spring表達式語言評估bean表達式
是否可以刪除符號@
和#
?
所以新的表達會像expressionUtil.substractDates(fromDate,toDate)
..
我不知道你的動機是什麼; fromDate
和toDate
是變量,由#
表示,@
表示需要諮詢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);
MapAccessor將是我的最佳選擇,變量是動態的在每次評估中。 – RiyasAbdulla
難道你不覺得如果可能的話,春天就不會有'@'和'#'了嗎? – 2017-04-24 05:23:46
檢查編輯這個答案..有可能刪除@我打算避免@和#。 http://stackoverflow.com/questions/11616316/programmatically-evaluate-a-bean-expression-with-spring-expression-language/11616942?noredirect=1#comment74193865_11616942 – RiyasAbdulla