Consider a Spring Boot service method annotated with @Cacheable. What is the behavior when this method is called multiple times with the same input?
public class ProductService { @Cacheable("products") public Product getProductById(Long id) { simulateSlowService(); return new Product(id, "Product " + id); } private void simulateSlowService() { try { Thread.sleep(3000L); } catch (InterruptedException e) { throw new IllegalStateException(e); } } }
Think about how caching avoids repeated work for the same input.
The @Cacheable annotation tells Spring to cache the method's result for each unique argument. On subsequent calls with the same argument, the cached value is returned immediately without executing the method body again.
Choose the correct @Cacheable annotation usage to cache a method result in cache named "users" using the method's first argument as the key.
public User getUserById(Long id) { ... }Remember the SpEL syntax for keys uses # before parameter names.
The correct syntax uses cacheNames or value for cache name and SpEL expression #id to refer to the method parameter named id.
Given the following Spring service, why is the caching not working as expected?
public class OrderService { @Cacheable("orders") public Order getOrder(Long id) { return fetchOrderFromDb(id); } public Order fetchOrderFromDb(Long id) { // Simulate DB call return new Order(id, "Order " + id); } public Order getCachedOrder(Long id) { return getOrder(id); } }
Think about how Spring AOP proxies work and method calls inside the same class.
Spring uses proxies to apply caching. Internal method calls within the same class bypass the proxy, so @Cacheable is not triggered when getOrder is called from getCachedOrder.
Consider this Spring Boot service method:
@Cacheable("items")
public String getItemName(int id) {
System.out.println("Fetching item " + id);
return "Item" + id;
}What will be printed to the console when calling getItemName(1) and then getItemName(2)?
Remember caching stores results per unique argument.
Each unique argument causes the method to execute once. So calling with 1 prints once, then calling with 2 prints once. Both calls print because arguments differ.
In Spring Boot, when a method annotated with @Cacheable returns null, what happens by default?
Think about why caching nulls might be problematic.
By default, Spring does not cache null return values to avoid caching absence of data. The method runs every time if it returns null.