Spring / Spring Boot 4 Basics Interview Questions
What is Spring Boot's caching abstraction and how do you use it?
Spring Boot 4 provides a caching abstraction that decouples application code from specific cache implementations. Using @EnableCaching and method-level annotations, you can cache method results and evict them declaratively.
// Enable caching: @SpringBootApplication @EnableCaching public class App { ... } // Service with caching: @Service public class ProductService { // Cache the result by productId: @Cacheable(value = "products", key = "#productId") public ProductDto findById(String productId) { return productRepo.findById(productId) // only called on cache miss .map(this::toDto) .orElseThrow(); } // Update the cache after saving: @CachePut(value = "products", key = "#result.id") public ProductDto save(Product product) { Product saved = productRepo.save(product); return toDto(saved); // returns updated value AND updates cache } // Evict from cache on delete: @CacheEvict(value = "products", key = "#productId") public void delete(String productId) { productRepo.deleteById(productId); } // Evict all cache entries: @CacheEvict(value = "products", allEntries = true) public void clearAll() { } } # Configuring the cache provider in application.yml: # Simple (in-memory, default when no other cache is configured): spring: cache: type: simple # Redis cache: spring: cache: type: redis redis: time-to-live: 600s data: redis: host: localhost port: 6379 # Caffeine (high-performance in-memory): spring: cache: type: caffeine caffeine: spec: maximumSize=1000,expireAfterWrite=300s
More Related questions...