Principes fondamentaux de l’abstraction de cache Spring
Utilisez @Cacheable, @CachePut et @CacheEvict pour ajouter une mise en cache sans toucher à la logique métier.
Principes fondamentaux de l’abstraction de cache Spring est une leçon Spring Boot 4 Complete Guide gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Boot 4 Complete Guide, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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.
Questions Fréquemment Posées
La leçon « Principes fondamentaux de l’abstraction de cache Spring » est-elle gratuite ?
Oui — le texte complet de « Principes fondamentaux de l’abstraction de cache Spring » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Boot 4 Complete Guide, passe à CoddyKit PRO. Le cours Spring Boot 4 Complete Guide comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Principes fondamentaux de l’abstraction de cache Spring » ?
Utilisez @Cacheable, @CachePut et @CacheEvict pour ajouter une mise en cache sans toucher à la logique métier. Tu pratiques Spring Boot 4 Complete Guide avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Spring Boot 4 Complete Guide ?
Aucune expérience préalable n'est requise. Spring Boot 4 Complete Guide sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.
Combien de temps prend la leçon « Principes fondamentaux de l’abstraction de cache Spring » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Spring Boot 4 Complete Guide ?
Oui. Chaque leçon Spring Boot 4 Complete Guide inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Principes fondamentaux de l’abstraction de cache Spring
- Mise en cache en mémoire et réglage de Caffeine
- Mise en cache distribuée avec Redis et TTL
- Ruée sur le cache, invalidation et cohérence