Spring 缓存抽象基础
使用 @Cacheable、@CachePut 和 @CacheEvict 添加缓存,无需修改业务逻辑。
Spring 缓存抽象基础 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「Spring 缓存抽象基础」课时是免费的吗?
是的 — 「Spring 缓存抽象基础」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
「Spring 缓存抽象基础」这节课中我会学到什么?
使用 @Cacheable、@CachePut 和 @CacheEvict 添加缓存,无需修改业务逻辑。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Complete Guide 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「Spring 缓存抽象基础」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?
能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Spring 缓存抽象基础
- 使用 Caffeine 调优内存缓存
- 使用 Redis 与 TTL 实现分布式缓存
- 缓存击穿、失效与一致性