What is Spring Boot caching with @Cacheable?
Why Interviewers Ask This
This question targets practical, hands-on experience with Spring Boot. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
Spring Boot's caching abstraction provides declarative caching support with multiple backend options. Add: spring-boot-starter-cache. Enable: @EnableCaching on @Configuration. Core annotations: @Cacheable("users") — cache the return value. On subsequent calls with the same parameters, returns cached value without executing the method. Key defaults to method parameters: @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { return userRepository.findById(id).orElseThrow(); }. @CachePut(value = "users", key = "#result.id") — update the cache with the returned value (always executes the method). @CacheEvict(value = "users", key = "#id") — remove from cache. @CacheEvict(value = "users", allEntries = true) — clear the entire cache. @Caching — combine multiple cache operations on one method. Cache providers: Simple (default — ConcurrentHashMap), EhCache, Caffeine (in-memory, high performance), Redis (distributed cache). Redis cache config: add spring-boot-starter-data-redis → Spring Boot auto-configures Redis as cache backend. Customize: @Bean public CacheManager cacheManager(RedisConnectionFactory rcf) { RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)); return RedisCacheManager.builder(rcf).cacheDefaults(config).build(); }. Condition: @Cacheable(condition = "#id > 0", unless = "#result == null") — conditional caching. SpEL in key: key = "#user.id + ':'+ #user.version".
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Spring Boot answers easy to follow.
Previous
What is Spring AOP (Aspect-Oriented Programming)?
Next
What is Spring Data JPA query methods and JPQL?