Spring Boot 4 Microservices & REST APIs · Aula

@Cacheable, @CachePut, @CacheEvict

Controle o comportamento do cache com precisão.

Aula 2 de 413 etapas

@Cacheable, @CachePut, @CacheEvict é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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
Grátis para começar

Aprenda Java com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
24
Aulas
93

Perguntas Frequentes

A aula “@Cacheable, @CachePut, @CacheEvict” é grátis?

Sim — o texto completo de “@Cacheable, @CachePut, @CacheEvict” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.

O que vou aprender em “@Cacheable, @CachePut, @CacheEvict”?

Controle o comportamento do cache com precisão. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?

Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “@Cacheable, @CachePut, @CacheEvict”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?

Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. A abstração de cache do Spring
  2. @Cacheable, @CachePut, @CacheEvict
  3. Redis como provedor de cache
  4. TTL e invalidação do cache
← Voltar para Spring Boot 4 Microservices & REST APIs