如何告诉Spring缓存不要在@Cacheable批注中缓存空值 [英] How do I tell Spring cache not to cache null value in @Cacheable annotation

查看:972
本文介绍了如何告诉Spring缓存不要在@Cacheable批注中缓存空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以指定如果该方法返回空值,那么不要将结果缓存在此类方法的@Cacheable批注中?

Is there a way to specify that if the method returns null value, then don't cache the result in @Cacheable annotation for a method like this?

@Cacheable(value="defaultCache", key="#pk")
public Person findPerson(int pk) {
   return getSession.getPerson(pk);
}

更新: 这是去年11月提交的有关缓存空值的JIRA问题,该问题尚未解决: [#SPR-8871] @Cachable条件应允许引用返回值-Spring Projects Issue Tracker

Update: here is the JIRA issue submitted regarding caching null value last November, which hasn't resolved yet: [#SPR-8871] @Cachable condition should allow referencing return value - Spring Projects Issue Tracker

推荐答案

Hooray,从Spring 3.2开始,该框架允许使用Spring SPEL和unless进行此操作.来自Cacheable的Java文档中的注释:

Hooray, as of Spring 3.2 the framework allows for this using Spring SPEL and unless. Note from the java doc surrounding Cacheable:

http://static.springsource .org/spring/docs/3.2.x/javadoc-api/org/springframework/cache/annotation/Cacheable.html

公共抽象字符串,除非

public abstract String unless

用于否决方法缓存的Spring Expression Language(SpEL)属性.

Spring Expression Language (SpEL) attribute used to veto method caching.

与condition()不同,此表达式是在调用方法后求值的,因此可以引用结果.默认值为",表示永远不会否决缓存.

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是在调用该方法之后求值的.这非常有道理,因为如果密钥已经在缓存中,则该方法将永远不会执行.

The important aspect is that unless is evaluated after the method has been called. This makes perfect sense because the method will never get executed if the key is already in the cache.

因此,在上面的示例中,您只需进行如下注释(#result可用于测试方法的返回值):

So in the above example you would simply annotate as follows (#result is available to test the return value of a method):

@Cacheable(value="defaultCache", key="#pk", unless="#result == null")
public Person findPerson(int pk) {
   return getSession.getPerson(pk);
}

我可以想象这种情况是由于使用可插拔缓存实现(例如Ehcache)而实现的,该实现允许对null进行缓存.根据您的用例场景,可能不希望如此.

I would imagine this condition arises from the use of pluggable cache implementations such as Ehcache which allows caching of nulls. Depending on your use case scenario this may or may not be desirable.

这篇关于如何告诉Spring缓存不要在@Cacheable批注中缓存空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆