How can caching be implemented in Spring MVC?

Caching in Spring MVC stores the results of expensive or frequently-called methods so repeated calls with the same input can be served from memory instead of recomputing them. Spring's caching abstraction lets you add caching declaratively with annotations, independent of the underlying cache provider.

Key Points: • @EnableCaching on a configuration class turns on Spring's annotation-driven cache management. • @Cacheable wraps a method so results are stored under a cache name and key, and cache hits skip the method body entirely. • @CacheEvict and @CachePut let you remove or refresh stale entries when underlying data changes. • Spring is provider-agnostic — you can back it with EhCache, Redis, Hazelcast, or Caffeine by supplying the right CacheManager bean. • Cache keys default to the method arguments but can be customized with SpEL via the key attribute.

Example: A product catalog service might annotate its findById(id) method with @Cacheable("products"), so the first lookup hits the database but every subsequent call for the same id returns instantly from the cache until it's evicted.

Code Example:

@Configuration
@EnableCaching
public class CacheConfig {
    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("items");
    }
}

@Service
public class ItemService {
    @Cacheable("items")
    public Item findById(Long id) {
        return itemRepository.findById(id).orElseThrow();
    }
}

Interview Tip: A concise interview answer is:

"I enable caching with @EnableCaching and annotate expensive read methods with @Cacheable, naming a cache region so repeated calls return from memory instead of hitting the database. For invalidation I pair it with @CacheEvict or @CachePut, and back the abstraction with a real provider like Redis or EhCache in production."