Performance: @Cacheable for read caching
This affects the speed of serving repeated read requests by avoiding repeated method executions and database hits.
@Cacheable("dataCache") @GetMapping("/data") public Data getData() { return database.queryData(); }
@GetMapping("/data") public Data getData() { return database.queryData(); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching, direct DB call | N/A | N/A | Higher due to slower server response | [X] Bad |
| @Cacheable caching method result | N/A | N/A | Lower due to faster server response | [OK] Good |
@Cacheable in a Spring Boot application?@Cacheable does@Cacheable stores the output of a method so that if the method is called again with the same inputs, it returns the stored result instead of running the method again.@Cacheable on a method named getUserById with cache name "users"?@Cacheable is cacheNames.@Cacheable(cacheNames = "users") which is correct syntax for Spring Boot caching.getData(5) is called twice?@Cacheable(cacheNames = "dataCache")
public int getData(int id) {
System.out.println("Fetching data for " + id);
return id * 2;
}getData(5) runs the method and prints "Fetching data for 5". The result (10) is cached.@Cacheable:@Cacheable(cacheNames = "items")
public Item getItem(Long id) {
return itemRepository.findById(id).get();
}
// Usage
getItem(null);@EnableCaching must be present on a @Configuration class to activate Spring's caching support. Without it, @Cacheable has no effect and caching fails silently.NullValue.INSTANCE in the default key generator, no exception from cache key. Methods do not need to be static.findProduct(String category, int id) but only cache when category is not null or empty. Which @Cacheable usage correctly implements this conditional caching?conditioncondition attribute controls when caching happens. It caches only if the condition is true.category is not null and not empty, matching the requirement. @Cacheable(cacheNames = "products", unless = "#category == null || #category == ''")
public Product findProduct(String category, int id) { ... } uses unless which caches unless the condition is true, so it inverts logic. @Cacheable(cacheNames = "products", key = "#category + #id")
public Product findProduct(String category, int id) { ... } only sets key, no condition. @Cacheable(cacheNames = "products", condition = "#id > 0")
public Product findProduct(String category, int id) { ... } caches based on id, not category.Pass the test and this pattern moves unknown