Grundlagen der Spring-Cache-Abstraktion
Verwenden Sie @Cacheable, @CachePut und @CacheEvict, um Caching hinzuzufügen, ohne die Geschäftslogik anzupassen.
Grundlagen der Spring-Cache-Abstraktion ist eine kostenlose Spring Boot 4 Complete Guide-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Spring Boot 4 Complete Guide-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Spring Boot 4 Complete Guide-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.
Häufig gestellte Fragen
Ist die Lektion „Grundlagen der Spring-Cache-Abstraktion“ kostenlos?
Ja — der vollständige Text von „Grundlagen der Spring-Cache-Abstraktion“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Spring Boot 4 Complete Guide-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Spring Boot 4 Complete Guide-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Grundlagen der Spring-Cache-Abstraktion“?
Verwenden Sie @Cacheable, @CachePut und @CacheEvict, um Caching hinzuzufügen, ohne die Geschäftslogik anzupassen. Du übst Spring Boot 4 Complete Guide mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Spring Boot 4 Complete Guide zu starten?
Keine Vorkenntnisse erforderlich. Spring Boot 4 Complete Guide auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „Grundlagen der Spring-Cache-Abstraktion“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Spring Boot 4 Complete Guide-Lektion Code schreiben und ausführen?
Ja. Jede Spring Boot 4 Complete Guide-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Grundlagen der Spring-Cache-Abstraktion
- In-Memory-Caching mit Caffeine-Optimierung
- Verteiltes Caching mit Redis und TTLs
- Cache Stampede, Invalidierung und Konsistenz