5
votes

Following @Cacheable annotation

@Cacheable(value="books", key="#isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
  • looks up in the cache based on the key
  • if found return the result from cache
  • if not found evaluates method
  • updates the cache
  • return the result

So that next time this method is called with same arguments it will be fetched from cache.

What I want instead is just to

  • Look up in the cache based on key
  • if found return the result from cache
  • if not found return null

I don't want to update the cache in case of cache-miss, is there any way to do this using spring Annotation

1
This isn't really the use-case for the @Cacheable annotation, and it's not really a common use case at all, so I'd guess that no you can't do this with spring annotations, and that you'll have to write a findBookInCache(ISBN isbn) method yourself. - beerbajay

1 Answers

8
votes

Here is what I ended up with, trick was to use 'unless' to our advantage

@Cacheable(value="books", key="#isbn", unless = "#result == null")
public Book findBookFromCache(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
{
    return null;
}

this method

  • Looks up in the cache based on key
  • if found return the result from cache
  • if not found evaluates method that return null
  • return value is matched with unless condition (which always return true)
  • null value do not get cached
  • null value is returned to caller