Search code examples
javaspringcachingspring-cache

Clearing cache from a method annotated with @Cacheable


I have a method annotated with @Cacheable. If an exception is captured inside the method, I want the cache to be cleared. However, it seems that the cache is loaded in an aspect that is executed after the line that clears it. Therefore, when an Exception is captured in the method, even though the cache is cleared, the empty string result stays in the cache.

Where should I clear the cache from?

@Cacheable("myCache") 
public String myMethod() {
    String result="";
    try {
        result = doSomething();
    } catch (Exception e) {
        cacheManager.getCache("myCache").clear();
    }
    return token;
}

Solution

  • Okay - there's an attribute on the annotation you can use. The following example is from (http://websystique.com/spring/spring-4-cacheable-cacheput-cacheevict-caching-cacheconfig-enablecaching-tutorial/)

    unless : Conditional Caching, applies to return value of method. Item will be cached, unless the condition mentioned in ‘unless’ met. Note that condition applies to return value of method.#result refers to method return value.

    @Cacheable(value="products", key="#product.name", condition="#product.price<500", unless="#result.outofstock")
    public Product findProduct(Product product){
    ..
    return aproduct;
    } 
    

    So you could have unless="#result.length() == 0" and return an empty string on the error case or any other time you don't want the result cached.