Spring 表达式语言 (SpEL) 中的 Elvis 运算符
我在 SpEL 中使用 elvis 运算符时发现一些奇怪的行为。如果我没有将 elvis 表达式括在方括号“()”中,则返回 elvis 运算符的结果,并忽略表达式的其余部分。显示以下行为的示例代码:
HashMap<String, String> facts = new HashMap<String, String>();
facts.put("flag", "flagvalue");
String expressionString;
Expression expression;
Object expressionResult;
expressionString = "[flag]?:'' matches '(?i)flagvalue'";
expression = new SpelExpressionParser().parseExpression(expressionString);
expressionResult = expression.getValue(facts);
System.out.println("Unexpected Result:" + expressionResult);
expressionString = "([flag]?:'') matches '(?i)flagvalue'";
expression = new SpelExpressionParser().parseExpression(expressionString);
expressionResult = expression.getValue(facts);
System.out.println("Expected Result:" + expressionResult);
输出:
Unexpected Result:flagvalue
Expected Result:true
奇怪的部分是,当值不在哈希图中时(即注释facts.put 行),elvis 运算符似乎工作正常,并且两个表达式都按预期返回 false。
(使用 spring-framework-3.0.5)
I'm seeing some trange behaviour using the elvis operator in SpEL. If I don't surround the elvis expression in brackets "()" then the result of the elvis operator is returned and the rest of the expression is ignored. Sample Code showing the behaviour below:
HashMap<String, String> facts = new HashMap<String, String>();
facts.put("flag", "flagvalue");
String expressionString;
Expression expression;
Object expressionResult;
expressionString = "[flag]?:'' matches '(?i)flagvalue'";
expression = new SpelExpressionParser().parseExpression(expressionString);
expressionResult = expression.getValue(facts);
System.out.println("Unexpected Result:" + expressionResult);
expressionString = "([flag]?:'') matches '(?i)flagvalue'";
expression = new SpelExpressionParser().parseExpression(expressionString);
expressionResult = expression.getValue(facts);
System.out.println("Expected Result:" + expressionResult);
Output:
Unexpected Result:flagvalue
Expected Result:true
The strange part is when the value is not in the hashmap (i.e comment the facts.put line) the elvis operator appears to work fine and both expressions return false as expected.
(using spring-framework-3.0.5)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您需要将示例扩展为 Java 表达式来理解差异,如下所示:
which prints
我还没有查看实现内部,但我猜
'' 匹配 '(?i )flagvalue'
将首先被求值,因为matches
是表达式树视图中的嵌套运算符。希望这有帮助。
I think you need to expand your example to the Java expression to understand the difference, which would look like this:
which prints
I haven't had a look inside the implementation, but I guess the
'' matches '(?i)flagvalue'
will be evaluated at first, becausematches
is a nested operator in the view of an expression tree.Hope this helps.