0Pricing
Spring Boot 4 Microservices & REST APIs · Leçon

@Cacheable, @CachePut, @CacheEvict

Contrôlez précisément le comportement du cache.

@Cacheable, @CachePut, @CacheEvict est une leçon Spring Boot 4 Microservices & REST APIs gratuite sur CoddyKit. Ceci est la leçon 2 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 Microservices & REST APIs, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Boot 4 Microservices & REST APIs comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

The Three Cache Annotations

Spring offers three method-level cache annotations:

  • @Cacheable — read-through, store the result
  • @CachePut — always run, update the cache
  • @CacheEvict — remove entries

@Cacheable

@Cacheable checks the cache first; on a miss it runs the method and stores the result.

@Cacheable("products")
public Product findById(Long id) {
    return repository.findById(id).orElseThrow();
}

Conditional Caching

Use condition to cache only when a predicate holds, and unless to skip caching certain results.

@Cacheable(value = "products",
    unless = "#result == null")
public Product findById(Long id) { ... }

@CachePut

@CachePut always executes the method and stores the returned value — ideal for update methods that should refresh the cache.

@CachePut(value = "products", key = "#product.id")
public Product update(Product product) {
    return repository.save(product);
}

Cacheable vs CachePut

@Cacheable may skip the method on a hit; @CachePut never skips. Never put both on the same method — their behaviors conflict.

@CacheEvict

@CacheEvict removes an entry, typically after a delete or update that invalidates cached data.

@CacheEvict(value = "products", key = "#id")
public void delete(Long id) {
    repository.deleteById(id);
}

Evicting Everything

Use allEntries = true to clear an entire cache at once.

@CacheEvict(value = "products", allEntries = true)
public void reloadAll() {
    // bulk refresh
}

Evict Before or After

By default eviction happens after the method succeeds. Set beforeInvocation = true to evict even if the method throws.

@CacheEvict(value = "products",
    allEntries = true, beforeInvocation = true)
public void risky() { ... }

Grouping with @Caching

@Caching combines multiple cache operations on one method.

@Caching(
    put = @CachePut(value = "products", key = "#p.id"),
    evict = @CacheEvict(value = "productList",
        allEntries = true))
public Product save(Product p) {
    return repository.save(p);
}

Class-Level Config

@CacheConfig sets a default cache name for all methods in a class, reducing repetition.

@Service
@CacheConfig(cacheNames = "products")
public class ProductService {
    @Cacheable(key = "#id")
    public Product findById(Long id) { ... }
}

Self-Invocation Caveat

Cache annotations work via proxies, so a method calling another cached method in the same class bypasses the cache. Call through a separate bean.

Quick Check

Test your understanding of the cache annotations.

Recap

You learned the three cache annotations:

  • @Cacheable — store and reuse results
  • @CachePut — always run and refresh
  • @CacheEvict — remove entries (allEntries, beforeInvocation)
  • Watch out for the self-invocation proxy caveat

Questions Fréquemment Posées

La leçon « @Cacheable, @CachePut, @CacheEvict » est-elle gratuite ?

Oui — le texte complet de « @Cacheable, @CachePut, @CacheEvict » 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 Microservices & REST APIs, passe à CoddyKit PRO. Le cours Spring Boot 4 Microservices & REST APIs comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « @Cacheable, @CachePut, @CacheEvict » ?

Contrôlez précisément le comportement du cache. Tu pratiques Spring Boot 4 Microservices & REST APIs 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 Microservices & REST APIs ?

Aucune expérience préalable n'est requise. Spring Boot 4 Microservices & REST APIs 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 2 sur 4.

Combien de temps prend la leçon « @Cacheable, @CachePut, @CacheEvict » ?

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 Microservices & REST APIs ?

Oui. Chaque leçon Spring Boot 4 Microservices & REST APIs 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

  1. L'abstraction de cache de Spring
  2. @Cacheable, @CachePut, @CacheEvict
  3. Redis comme fournisseur de cache
  4. TTL et invalidation du cache
← Retour à Spring Boot 4 Microservices & REST APIs