java / intermediate
Snippet
Declarative Method Caching with @Cacheable
Caching improves performance by storing the result of expensive operations. When @Cacheable is used, Spring checks the cache first; if the data exists for the given key, it returns it without executing the method.
snippet.java
1
2
3
4
5
6
7
8
@Servicepublic class PriceService {@Cacheable(value = "prices", key = "#productId")public BigDecimal getLatestPrice(String productId) {// Simulate slow database or API callreturn fetchFromExternalAPI(productId);}}
spring
Breakdown
1
@Cacheable(value = "prices", key = "#productId")
Specifies the cache name and the SpEL expression used to generate the unique lookup key.
2
return fetchFromExternalAPI(productId)
This code only runs if the cache does not already contain a value for this productId.