Spring evaluation language (SpEL) not throw exception when accessing invalid key in map

65
September 13, 2017, at 10:11 PM

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

Answer 1

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);
READ ALSO
While authenticating mongodb using java it is taking more time and throwing mongotimeoutException in case of wrong credential

While authenticating mongodb using java it is taking more time and throwing mongotimeoutException in case of wrong credential

After authentication i need to show message to end userBut, the exception is comming after 30 seconds in case when the user enters wrong credentials

63
Converting XML+XSL in HTML using Java

Converting XML+XSL in HTML using Java

We have data as XML and there are multiple formatting XSL stylesIt was working fine till now in IE

56
How can I parse a csv in low memory, using some parser in Java?

How can I parse a csv in low memory, using some parser in Java?

I used InputStream, and on parsing, if there is a "," in one column then it considers it as a separate columnex - abc, xyz, "m,n" then the parsed output is abc , xyz, m, n Here m and n are considered as separate columns

34
Spring JdbcTemplate &ldquo;insert into.. select from..&rdquo; not working

Spring JdbcTemplate “insert into.. select from..” not working

I am trying to execute following SQL with Spring JdbcTemplate:

41