为什么这个流& lambda表达式与SpEL声明一起工作?

时间:2015-08-21 04:08:40

标签: spring spring-el spring-cache

我正在尝试在Spring @Cache注释中使用Java 8流和lambda表达式。

我正在尝试使用以下内容:

@CacheEvict(value = "tags", allEntries = true, 
condition = "#entity.getTags().stream().anyMatch(tag -> tag.getId() == null)")

失败了:

SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
org.springframework.expression.spel.SpelParseException: 
EL1042E:(pos 40): Problem parsing right operand

但是,如果我将流移动到实体上的方法中,我能够使它工作。然后,注释的工作原理如下:

@CacheEvict(value = "tags", beforeInvocation=true, allEntries = true, 
condition = "#entity.containsNewTag()")

我宁愿不需要'containtsNewTag()'方法,如果可能的话,直接在SpEL表达式中使用流。可以这样做吗?

2 个答案:

答案 0 :(得分:5)

Spring Expression Language定义为in the developer guide。目前语言不支持您尝试做的事情。我还认为这是一个非常奇怪的地方放置这样的代码:一个可以单元测试的孤立方法确实更好。

答案 1 :(得分:0)

您可以使用以下语法(使用Collection Selection和'this')来实现您的意图

这里#root是您的实体,在选择项中,#this表示标签。

anyMatch示例:

"#root.getTags().?[#this.getId() == null].size() > 0"

示例allMatch:

"#root.getTags().?[#this.getId() == null].size() eq #root.getTags().size()"