The cache key is derived from the method parameters, and the method is skipped entirely on a hit.
@EnableCaching
@Configuration
class CacheConfig { }
@Service
class CatalogService {
@Cacheable("products")
public Product byId(Long id) {
System.out.println("loading " + id);
return repo.findById(id).orElseThrow();
}
@CacheEvict(value = "products", key = "#product.id")
public void update(Product product) { repo.save(product); }
}
byId(1) -> loading 1
byId(1) -> (nothing printed - served from cache)
update(p1); byId(1) -> loading 1
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-11