java / intermediate
Snippet
Declarative Caching with @Cacheable
Spring's caching abstraction allows you to transparently cache method results, significantly reducing database load for frequently accessed data.
snippet.java
1
2
3
4
5
6
7
8
@Servicepublic class ProductService {@Cacheable(value = "products", key = "#id")public Product findProductById(Long id) {simulateSlowService();return repository.findById(id);}}
spring
Breakdown
1
@Cacheable(value = "products", key = "#id")
Instructs Spring to check the 'products' cache using the 'id' parameter before executing the method.
2
simulateSlowService();
Represents a heavy operation that will only be executed if the result is not already in the cache.