Contents

Spring Cache

@EnableCaching

@Cachable ({"cache-name-1", "cache-name-2"})

  • will first check the cache addresses before actually invoking the method and then caching the result
  • if multiple cache used, will return if present in anyone

@CacheEvict(value="cache-name", allEntries=true)

  • eviction policy to manage cache size for faster lookup and low memory usage

@CachePut(value="cache-name")

  • avoid evicting too much of cache
  • selectively entries whenever we alter them
  • Cachable will not invoke method if present in cache; CachePut will always? invoke and update in cache

@Caching

for grouping multiple annotations of same type on same method (Java doesn’t allow it)

1
2
3
4
@Caching(evict = { 
  @CacheEvict("addresses"), 
  @CacheEvict(value="directory", key="#customer.name") })
public String getAddress(Customer customer) {...}

@CacheConfig

  • class level cache configuration common to all its methods annotated as cache
1
2
3
4
5
@CacheConfig(cacheNames={"addresses"})
public class CustomerDataService {

    @Cacheable
    public String getAddress(Customer customer) {...}

Conditional Parameters (all annotations)

  • Use SpEL expression
    condition="#customer.name=='Tom'"
  • based on result after method exec
    unless="#result.length()<64"

Reference

Spring Cache Baeldung