I am new to SpEL and below is a sample workable test that I used for testing.
public static void main(String[] args) {
Map<String,String> dictMap = new HashMap<>();
dictMap.put("key", "value");
Map<String, Object> rootObj = new HashMap<>();
rootObj.put("d", dictMap);
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("['d']['wrongkey']");
String msg = (String) exp.getValue(new StandardEvaluationContext(rootObj), String.class);
System.out.println(msg);
}
I expected that the expression should throw exception because there is no key named "wrongkey" in dictMap context. However, it print "null".
Is there any setting that I can use to force the expression evaluation throw exception?
Thank you
Not sure why there should be an exception.
Look, do we have an exception in this case?
dictMap.get("wrongkey");
No, because that is how Java works. The SpEL in Spring is fully based on Java nature. So, here it only delegates to the normal Java's Map.get()
.
To make it throw an exception you should add into the StandardEvaluationContext
a MapAccessor
. And that one already has desired logic which throws exception when there is no requested key:
Map<?, ?> map = (Map<?, ?>) target;
Object value = map.get(name);
if (value == null && !map.containsKey(name)) {
throw new MapAccessException(name);
}
return new TypedValue(value);