Spring Boot 4 Complete Guide · Lección

Fundamentos de la abstracción de caché de Spring

Use @Cacheable, @CachePut y @CacheEvict para añadir caché sin modificar la lógica de negocio.

Lección 1 de 413 pasos

Fundamentos de la abstracción de caché de Spring es una lección gratuita de Spring Boot 4 Complete Guide en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Complete Guide, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Complete Guide incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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 argument
  • key = "#book.id" — use a property of the argument
  • key = "#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, and unless.
  • @CachePut always runs then updates the cache — ideal for writes.
  • @CacheEvict removes entries (one key or allEntries), optionally beforeInvocation.
  • Group operations with @Caching, and beware the self-invocation proxy trap.

The result: caching declared declaratively, with business logic untouched.

Gratis para empezar

Aprende Java con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
21
Lecciones
84

Preguntas frecuentes

¿La lección «Fundamentos de la abstracción de caché de Spring» es gratis?

Sí — el texto completo de «Fundamentos de la abstracción de caché de Spring» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Complete Guide, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Complete Guide incluye 4 lecciones en total.

¿Qué aprenderé en «Fundamentos de la abstracción de caché de Spring»?

Use @Cacheable, @CachePut y @CacheEvict para añadir caché sin modificar la lógica de negocio. Practicas Spring Boot 4 Complete Guide con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Spring Boot 4 Complete Guide?

No se requiere experiencia previa. Spring Boot 4 Complete Guide en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «Fundamentos de la abstracción de caché de Spring»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Complete Guide?

Sí. Cada lección de Spring Boot 4 Complete Guide incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Fundamentos de la abstracción de caché de Spring
  2. Caché en memoria con ajuste de Caffeine
  3. Caché distribuida con Redis y TTL
  4. Avalancha de caché, invalidación y coherencia
← Volver a Spring Boot 4 Complete Guide