Search code examples
javaspringcachingspring-cache

@Cachable on methods without input parameters?


I'm having a problem with @org.springframework.cache.annotation.Cachable annotation:

@Bean
public ConcurrentMapCache cache() {
    return new ConcurrentMapCache(CACHE);
}

@Cacheable(CACHE)
public String getApi() {
    return "api";
}

@Cacheable(CACHE)
public String getUrl() {
    return "url";
}

usage:

assertEquals("api", service.getApi()); //OK
assertEquals("url", service.getUrl()); //FAILURE. this returns also "api"

So, why does @Cachable not create a cache result by method name if method signature does not contain any input parameters?


Solution

  • Try this

    @Cacheable(value = CACHE, key = "#root.method.name")
    

    Or even

    @Cacheable(value = CACHE, key = "#root.methodName")
    

    You need to tell spring to use method name as key. You can use SPEL for this. Here is the doc with various other options.