Declarative Caching
Spring caching abstraction provides set of Java annotations:
| Annotation | Description |
|---|---|
| @Cacheable | Triggers cache population. |
| @CacheEvict | Triggers cache eviction. |
| @CachePut | Updates the cache without interfering with the method execution. |
| @Caching | Regroups multiple cache operations to be applied on a method. |
| @CacheConfig | Shares some common cache-related settings at class-level. |
Store method result in cache
@Cacheable("books")
public Book getBook(Long id) {...}
@Cacheable(cacheNames="books", key="#isbn")
public Book findBook(String isbn, boolean includeArchived) {...}
@Cacheable(cacheNames="books", key="#isbn", cacheManager="globalCacheMaager")
public Book findBook(String isbn, boolean includeArchived) {...}
@Cacheable("books", sync=true)
public Book getBook(Long id) {...}
@Cacheable("books")
public Mono<Book> getBook(Long id) {...}
- Method result (object of type Book) is stored in 'books' cache with key 'id'
- You can define key explicitly
- You can define CacheManeger if multiple are used
- You can define if cache should allow synchronized access for parallel use cases
- The reactive approach is spupported from Spring 6.1
Custom Key generation
- You can choose which method's arguments are included in Key generation in @Cacheable(key=) annotation
- Or you cane specify custom Key Generator in @Cacheable(keyGenerator=) annotation
- The 'key' and 'keyGenerator' parameters are mutually exclusive
Cutom Cache resolution
- The supported Cache backends are automatically resolved by Spring Boot
- Custom CacheManager and CacheREsolver can be implemented
Conditional caching
You can use 'condition' atribute of @Cacheable annotation and define condition as SpEL expression.
@Cacheable(cacheNames="books", condition="#id%2 == 0")
public Book getBook(Long id) {...}