首页 > 解决方案 > 带有 ResponseEntity 类型的 spring 表达式

问题描述

实际上,我正在使用 Spring Cache 缓存一个 Http 响应,现在我想设置一个条件,即仅在响应有效时才更新缓存。

@Cacheable(value = CACHE, condition = "#result.body.responseData.toLowerCase().contains("A")")
public ResponseEntity<ProcessMqReqPostResponseBody> sendMqRequest(Integer pageNumber, Integer pageSize, String sortOrder, String merchantId) {
//Method Implementation
}

没有这个条件,我可以很好地测试我的缓存,但是当我添加这个条件时,我得到了错误

org.springframework.expression.spel.SpelEvaluationException:EL1007E:在 null 上找不到属性或字段“body”

我不明白,因为我可以在我的测试中输出 responseEntity 并且它不为空。这种行为正确吗?

谢谢,阿什利

标签: javaspringspring-boot

解决方案


Spring 的行为是正确的,因为您正在编写一个将根据结果起作用的条件。

#result值始终null在方法执行之前,结果值仅在方法执行后填充。

如果你想测试这个,你可以改变你的条件,方法根本不会被缓存,也不会出错。

@Cacheable(value = CACHE, condition = "#result != null and #result.body.responseData.toLowerCase().contains(\"A\")")

如果您想对结果采取行动,您只能使用unless元素来执行此操作。

与 condition() 不同,此表达式在方法被调用后进行评估,因此可以引用结果。

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html#unless--


推荐阅读