Consider a Spring Boot method annotated with @CachePut. What is the behavior when this method is executed?
Think about whether the method runs or if the cache is just read.
@CachePut always runs the method and then updates the cache with the new result. It does not skip method execution like @Cacheable.
Choose the correct @CachePut annotation syntax to update the cache named users using the id property of the user parameter as the key.
Remember to use SpEL (Spring Expression Language) syntax for keys.
The key must be a SpEL expression starting with # to access method parameters. Option B correctly uses #user.id.
Given this method:
@CachePut(value = "products", key = "#product.id")
public Product updateProduct(Product product) {
productRepository.save(product);
return product;
}Why might the cache not update after calling updateProduct?
Think about how Spring AOP proxies work with self-invocation.
Spring cache annotations work via proxies. If the method is called from the same class (self-invocation), the proxy is bypassed and caching annotations are not applied.
Given this method:
@CachePut(value = "users", key = "#user.id")
public User updateUser(User user) {
return user;
}And these calls:
updateUser(new User(1, "Alice")); updateUser(new User(1, "Bob"));
What is the cached value for key 1?
Consider what happens when the same key is updated twice.
@CachePut updates the cache with the returned value each time. The second call overwrites the first cached value for key 1.
Which reason best explains why @CachePut is preferred over @Cacheable for methods that update data?
Think about cache consistency when data changes.
@CachePut ensures the method runs and the cache is updated with fresh data. @Cacheable may skip method execution and return stale cache data, which is not suitable for updates.