我得到以下代码:
@Cacheable(value = "cacheName", key = "#someMap.toString()", unless="#result.error")
public List<Book> methodName(Map<Integer, Integer> someMap) throws BookException {
//...
该方法抛出 BookException ,我希望避免在发生这种情况时缓存结果。但是当我执行方法时:
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'error' cannot be found on object of type 'java.util.ArrayList' - maybe not public?
答案 0 :(得分:1)
由于结果是Collection(在本例中为List),因此您只能使用附加到该类的操作。因此,您可以说unless="#result != null"
或unless="#result.size() > 0"
错误不是List
类中的有效方法。
答案 1 :(得分:1)
如果在带注释的方法中引发异常并将其进一步传播,则不必捕获它(似乎是您的情况)。在这种情况下,缓存中没有要存储的键值对,因此默认情况下您会获得所需的行为:)
简而言之:消除“除非”的条件并享受。
答案 2 :(得分:0)
尝试使用此配置,当发生异常时它不会缓存数据:
@Cacheable(值=“ sendAndReceiveMessage”,键=“ {#requestData.toString()}”,除非=“ #result instanceof T(java.lang.Exception)”)
答案 3 :(得分:0)
不要抛出异常。而是使用try / catch块,并在catch块中为列表分配空值。同时使用@Cacheable(value = "cacheName", key = "#someMap.toString()", unless="#result==null")
。此技巧适用于包括集合在内的所有对象。