1. Introduction
The @CachePut
annotation in Spring Framework is used to update the cache without interfering with the method execution. Unlike @Cacheable
, which may skip the method execution if the value is already in the cache, @CachePut
always executes the method and updates the cache with the result.
2. Use Case
Use @CachePut
when:
- You want the method to execute every time (e.g., an update operation).
- You want to update the cache with the method result.
3. Syntax
@CachePut(cacheNames = "cacheName", key = "#id") public ReturnType methodName(Type id) { // logic that updates data return updatedValue; }
4. How It Works
- The method will execute regardless of the cache state.
- The result of the method execution will be placed into the cache.
- Subsequent reads using
@Cacheable
with the same key can benefit from the updated cache.
5. Example
1. Setup cache in Spring Boot application
Setup cache in Spring Boot application
@SpringBootApplication @EnableCaching public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } }
2. Create a service using @CachePut
@Service public class ProductService { private final Map<Long, Product> database = new ConcurrentHashMap<>(); public ProductService() { database.put(1L, new Product(1L, "iPhone", 75000)); } @Cacheable(value = "products", key = "#id") public Product getProductById(Long id) { System.out.println("Fetching from DB for id: " + id); return database.get(id); } @CachePut(value = "products", key = "#product.id") public Product updateProduct(Product product) { System.out.println("Updating product in DB and cache: " + product); database.put(product.getId(), product); return product; } }
3. Sample Controller
@RestController @RequestMapping("/products") public class ProductController { @Autowired private ProductService productService; @GetMapping("/{id}") public Product getProduct(@PathVariable Long id) { return productService.getProductById(id); } @PutMapping public Product updateProduct(@RequestBody Product product) { return productService.updateProduct(product); } }
4. Output Behavior
- First call to
GET /products/1
→ Hits DB and caches result. - Second call to
GET /products/1
→ Returns from cache. - Call
PUT /products
with updated product → Updates DB and also updates the cache due to@CachePut
. - Next call to
GET /products/1
→ Returns updated value from the cache.
5. Difference Between @CachePut
, @Cacheable
, and @CacheEvict
Annotation | Executes Method? | Reads from Cache? | Updates Cache? | When to Use? |
@Cacheable | No (if cached) | Yes | No | For reads, to avoid recomputation. |
@CachePut | Always | No | Yes | For writes/updates. |
@CacheEvict | Optional | No | No (removes) | For deletions, to clear cache. |