有没有办法指定如果方法返回空值,那么对于这样的方法不要将结果缓存在@Cacheable注解中?
@Cacheable(value="defaultCache", key="#pk")
public Person findPerson(int pk) {
return getSession.getPerson(pk);
}
更新: 这是去年 11 月提交的关于缓存空值的 JIRA 问题,尚未解决: [#SPR-8871] @Cachable condition should allow referencing return value - Spring Projects Issue Tracker
最佳答案
万岁,从 Spring 3.2 开始,框架允许使用 Spring SPEL 和 unless
进行此操作。来自围绕 Cacheable 的 java 文档的注释:
public abstract String unless
Spring Expression Language (SpEL) attribute used to veto method caching.
Unlike condition(), this expression is evaluated after the method has been called and can therefore refer to the result. Default is "", meaning that caching is never vetoed.
重要的一点是 unless
在方法被调用之后被评估。这很有意义,因为如果 key 已经在缓存中,该方法将永远不会被执行。
所以在上面的例子中你可以简单地注释如下(#result 可用于测试方法的返回值):
@Cacheable(value="defaultCache", key="#pk", unless="#result == null")
public Person findPerson(int pk) {
return getSession.getPerson(pk);
}
我想这种情况是由于使用了可插入的缓存实现,例如允许缓存空值的 Ehcache。根据您的用例场景,这可能是可取的,也可能是不可取的。
关于spring - 如何告诉 Spring 缓存不要在 @Cacheable 注释中缓存空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113725/