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);
}
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, 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
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.So in the above example you would simply annotate as follows (#result is available to test the return value of a method):
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.
update this answer is outdated now, for Spring 3.2 and later see Tech Trip's answer, OP: feel free to mark it as accepted.
I don't think that it's possible(even though there's conditional Cache eviction in Spring that can be executed after the method invocation with
@CacheEvict
parameter beforeInvocation set to false, which is default value) examining theCacheAspectSupport
class shows that the returned value is not stored anywhere before theinspectAfterCacheEvicts(ops.get(EVICT));
call.If Spring annotation
does not work ,you can try:
It works for me.