java / beginner
Snippet
Speeding Up Method Responses Using Cacheable
The @Cacheable annotation stores the return value of expensive operations in memory. When the method is invoked again with the same argument, Spring bypasses the method execution entirely and immediately returns the cached result, reducing response times and database load.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.springframework.cache.annotation.Cacheable;import org.springframework.cache.annotation.EnableCaching;import org.springframework.stereotype.Service;@Service@EnableCachingpublic class ProductService {@Cacheable(value = "products", key = "#id")public String fetchProductDetails(Long id) {// Simulating an expensive database or network operationreturn "Product Details for: " + id;}}
spring
Breakdown
1
@EnableCaching
Activates Spring's caching infrastructure and proxy support for the application.
2
@Cacheable(value = "products", key = "#id")
Specifies the target cache name ('products') and uses the 'id' parameter as the lookup key.
3
public String fetchProductDetails(Long id)
The method whose return value is cached upon first execution for each unique key.