The Spring Cache Abstraction Fundamentals
Use @Cacheable, @CachePut, and @CacheEvict to add caching without touching business logic.
The Spring Cache Abstraction Fundamentals is a free Spring Boot 4 Complete Guide lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Spring Boot 4 Complete Guide learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why a Cache Abstraction?
Caching stores the result of an expensive operation so the next identical call returns instantly. The naive approach scatters if (map.containsKey(key)) ... logic across your service methods, mixing caching with business logic.
Spring's Cache Abstraction solves this. You declare caching with annotations, and Spring weaves the logic in via AOP proxies. Your method body stays focused on the actual work.
- @Cacheable — return cached value if present, else run the method and store the result
- @CachePut — always run the method, then update the cache
- @CacheEvict — remove entries from the cache
Enabling Caching
The abstraction is opt-in. Add @EnableCaching to a configuration class (or your main application class). This tells Spring to scan for caching annotations and create the proxies that intercept your method calls.
Without a CacheManager bean, Spring Boot auto-configures a simple in-memory ConcurrentMapCacheManager — fine for development, but you'll swap it for Caffeine or Redis in production.
@SpringBootApplication
@EnableCaching
public class StoreApplication {
public static void main(String[] args) {
SpringApplication.run(StoreApplication.class, args);
}
}@Cacheable in Action
@Cacheable is the workhorse. On the first call with a given argument, Spring runs the method and stores the result under a key. On subsequent calls with the same argument, the method body is skipped entirely and the cached value is returned.
The value (or cacheNames) attribute names the logical cache. The key defaults to the method arguments.
@Service
public class BookService {
@Cacheable("books")
public Book findByIsbn(String isbn) {
// Simulates a slow database lookup
simulateSlowService();
return new Book(isbn, "Spring in Action");
}
}How the Cache Key Is Built
By default the key is derived from the method parameters. With one parameter, that parameter is the key. With multiple parameters, Spring uses a SimpleKey combining them.
You can take control with a SpEL expression in the key attribute. This is essential when only part of an argument should form the key.
key = "#isbn"— use the isbn argumentkey = "#book.id"— use a property of the argumentkey = "#root.methodName + #id"— combine metadata and arguments
@Cacheable(cacheNames = "books", key = "#book.isbn")
public Book refresh(Book book) {
return reload(book);
}Conditional Caching
Sometimes you only want to cache certain results. Two SpEL attributes help:
- condition — evaluated before the method runs; caching applies only if it is true
- unless — evaluated after the method runs (it can see the result via
#result); it vetoes caching when true
A common pattern: never cache null results, so a failed lookup isn't remembered.
@Cacheable(
cacheNames = "books",
key = "#isbn",
condition = "#isbn.length() > 0",
unless = "#result == null")
public Book findByIsbn(String isbn) {
return repository.lookup(isbn);
}@CachePut: Always Run, Always Update
Unlike @Cacheable, @CachePut always executes the method and then stores the returned value into the cache. Use it for create/update operations where you want the fresh result to populate the cache.
Pin the key to the same value @Cacheable reads, so a later findByIsbn sees the updated entry instead of a stale one.
@CachePut(cacheNames = "books", key = "#result.isbn")
public Book updateBook(Book book) {
return repository.save(book);
}Cacheable vs CachePut — The Key Decision
It is tempting to put @Cacheable on an update method, but that is a bug: @Cacheable may skip the method entirely if the key already exists, so your save never runs.
- Read methods that should short-circuit on a hit → @Cacheable
- Write methods that must always execute, but should refresh the cache → @CachePut
Never put both on the same method — their semantics conflict (one may skip, the other always runs).
@CacheEvict: Removing Entries
@CacheEvict removes data from the cache, typically on delete or when an entry becomes invalid. Target a single key, or wipe the whole cache with allEntries = true.
By default eviction happens after the method returns successfully. Set beforeInvocation = true to evict even if the method throws.
@CacheEvict(cacheNames = "books", key = "#isbn")
public void deleteBook(String isbn) {
repository.delete(isbn);
}
@CacheEvict(cacheNames = "books", allEntries = true)
public void reloadCatalog() {
repository.reloadAll();
}Composing Multiple Operations with @Caching
When one method needs several caching operations — for example updating one cache while evicting from another — use @Caching to group them. It accepts arrays of cacheable, put, and evict annotations.
This avoids the limitation that you cannot repeat the same annotation type directly on a method (in older Java) and keeps related operations together.
@Caching(
put = { @CachePut(cacheNames = "booksById", key = "#book.id") },
evict = { @CacheEvict(cacheNames = "bookSearch", allEntries = true) })
public Book save(Book book) {
return repository.save(book);
}The Self-Invocation Trap
Spring's caching works through a proxy that wraps your bean. The annotation only fires when the call enters the bean from outside. If a method calls another cached method on this, the call bypasses the proxy and caching is silently skipped.
- Move the cached method to a separate bean, or
- Inject a self-reference, or use
AopContext.currentProxy()
This is the same proxy limitation you see with @Transactional.
@Service
public class CatalogService {
public List<Book> report() {
// BUG: internal call -> proxy bypassed, NOT cached
return List.of(findByIsbn("123"));
}
@Cacheable("books")
public Book findByIsbn(String isbn) {
return repository.lookup(isbn);
}
}A Tiny Standalone Cache Demo
To see the caching concept without Spring, here is a plain Java program that memoizes results in a Map — exactly what @Cacheable automates for you. Run it and notice the second call is instant because it hits the cache.
import java.util.HashMap;
import java.util.Map;
public class Main {
static Map<String, String> cache = new HashMap<>();
static String findByIsbn(String isbn) {
if (cache.containsKey(isbn)) {
return cache.get(isbn) + " (from cache)";
}
try { Thread.sleep(200); } catch (InterruptedException e) {}
String book = "Book-" + isbn;
cache.put(isbn, book);
return book + " (computed)";
}
public static void main(String[] args) {
System.out.println(findByIsbn("123"));
System.out.println(findByIsbn("123"));
}
}Quick Check
You have an updateBook(Book book) method that must always persist the book to the database and refresh the cache so later reads see the new data. Which annotation is correct?
Recap
You learned the Spring Cache Abstraction and its three core annotations:
- @EnableCaching turns the feature on; a
CacheManager(default in-memory, later Caffeine/Redis) backs it. - @Cacheable short-circuits on a hit — ideal for reads. Tune it with
key,condition, andunless. - @CachePut always runs then updates the cache — ideal for writes.
- @CacheEvict removes entries (one key or
allEntries), optionallybeforeInvocation. - Group operations with @Caching, and beware the self-invocation proxy trap.
The result: caching declared declaratively, with business logic untouched.
Frequently asked questions
Is the “The Spring Cache Abstraction Fundamentals” lesson free?
Yes — the full text of “The Spring Cache Abstraction Fundamentals” is free to read here on the web, and the Spring Boot 4 Complete Guide course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Spring Boot 4 Complete Guide course, upgrade to CoddyKit PRO.
What will I learn in “The Spring Cache Abstraction Fundamentals”?
Use @Cacheable, @CachePut, and @CacheEvict to add caching without touching business logic. You practise Spring Boot 4 Complete Guide with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Spring Boot 4 Complete Guide?
No prior experience is required. Spring Boot 4 Complete Guide on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “The Spring Cache Abstraction Fundamentals” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Spring Boot 4 Complete Guide lesson?
Yes. Every Spring Boot 4 Complete Guide lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Spring Cache Abstraction Fundamentals
- In-Memory Caching with Caffeine Tuning
- Distributed Caching with Redis and TTLs
- Cache Stampede, Invalidation, and Consistency