0 day streak
java / intermediate
Snippet

Performance Optimization with @Cacheable

Spring Cache abstraction allows you to transparently cache expensive operations. Subsequent calls with the same ID will return the cached value instead of executing the method body.

snippet.java
java
1
2
3
4
5
6
7
8
@Service
public class ProductService {
@Cacheable(value = "products", key = "#id")
public Product getProductById(Long id) {
// Simulated slow database call
return repository.findById(id).orElseThrow();
}
}
spring
Breakdown
1
@Cacheable(value = "products", key = "#id")
Specifies the cache name and the dynamic key used for lookup.