Video in progress
How does the @Cacheable annotation in Spring work?
Before the method is called, Spring looks in the cache for a key built from the arguments. If it finds one, it returns the value without calling the method at all; if not, it runs the method and writes the result to the cache.
📖 Answer
@EnableCaching
@SpringBootApplication
class App { }
@Service
class ProductService {
@Cacheable(cacheNames = "products", key = "#id")
public ProductDto find(long id) {
return repo.findById(id).map(ProductDto::from).orElseThrow();
}
}
The first find(5) goes to the DB, and the result is written under the key products::5. The second find(5) doesn't touch the DB.
This works through a proxy: Spring creates a wrapper around ProductService and checks the cache there. That means:
- without
@EnableCachingthe annotation does nothing; - the method must be
public; - if you call
this.find(5)from inside the same class, the proxy is bypassed and the cache doesn't work.
If the Redis starter is on the classpath, Boot configures RedisCacheManager automatically.
Sign up to mark studied questions and save your progress.