@Cacheable, @CachePut, @CacheEvict
Controle con precisión el comportamiento de la caché
@Cacheable, @CachePut, @CacheEvict es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 2 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 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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
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
- 24
- Lecciones
- 93
Preguntas frecuentes
¿La lección «@Cacheable, @CachePut, @CacheEvict» es gratis?
Sí — el texto completo de «@Cacheable, @CachePut, @CacheEvict» 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 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
¿Qué aprenderé en «@Cacheable, @CachePut, @CacheEvict»?
Controle con precisión el comportamiento de la caché Practicas Spring Boot 4 Microservices & REST APIs 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 Microservices & REST APIs?
No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs 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 2 de 4.
¿Cuánto tiempo toma la lección «@Cacheable, @CachePut, @CacheEvict»?
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 Microservices & REST APIs?
Sí. Cada lección de Spring Boot 4 Microservices & REST APIs 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
- La abstracción de caché de Spring
- @Cacheable, @CachePut, @CacheEvict
- Redis como proveedor de caché
- TTL e invalidación de la caché