3.9 KiB
Spring Framework Cache Reference (Official)
Curated excerpts from the official Spring Framework reference documentation covering caching fundamentals and annotation usage. Source pages are from the Spring Framework Reference Guide 6.2.
Cache Abstraction Overview
-
Purpose: Transparently wrap expensive service methods and reuse results resolved from configured cache managers.
-
Enablement:
@Configuration @EnableCaching public class CacheConfig { @Bean public CacheManager cacheManager() { return new ConcurrentMapCacheManager("books"); } }Source: /integration/cache/annotations
-
Supported return types:
CompletableFuture, ReactorMono/Flux, blocking objects, and collections are all cacheable. For async/reactive types, Spring stores the resolved value and rehydrates it on retrieval.
Core Annotations
@Cacheable
- Cache the method invocation result using the provided cache name and key.
- Supports conditional caching with
condition(pre-invocation) andunless(post-invocation, access#result).
@Cacheable(cacheNames = "book", condition = "#isbn.length() == 13", unless = "#result.hardback")
public Book findBook(String isbn) { ... }
Source: /integration/cache/annotations
@CachePut and @CacheEvict
@CachePut: Always run the method and update cache entry with fresh result.@CacheEvict: Remove entries; useallEntries = trueorbeforeInvocationfor pre-call eviction.
@CacheEvict(cacheNames = "books", key = "#isbn", beforeInvocation = true)
public void reset(String isbn) { ... }
Source: /integration/cache/annotations
@Caching
- Bundle multiple cache operations on a single method:
@Caching(evict = {
@CacheEvict("primary"),
@CacheEvict(cacheNames = "secondary", key = "#isbn")
})
public Book importBooks(String isbn) { ... }
Source: /integration/cache/annotations
Store Configuration Highlights
-
Caffeine: Configure
CaffeineCacheManagerto create caches on demand.@Bean CacheManager cacheManager() { return new CaffeineCacheManager(); } -
XML alternative: Use
<cache:annotation-driven cache-manager="..."/>when annotation configuration is not feasible.<cache:annotation-driven cache-manager="cacheManager"/> <bean id="cacheManager" class="org.springframework.cache.caffeine.CaffeineCacheManager"/>
Reactive and Async Support
-
@Cacheableworks with asynchronous signatures:@Cacheable("books") public Mono<Book> findBook(ISBN isbn) { ... }@Cacheable(cacheNames = "foos", sync = true) public CompletableFuture<Foo> executeExpensiveOperation(String id) { ... }Source: /integration/cache/annotations
Additional Resources
spring-cache-doc-snippet.md: Excerpt of the narrative caching overview from the Spring documentation.- Refer to
cache-core-reference.mdfor expanded API reference material andcache-examples.mdfor progressive examples.