🍃 Spring Boot Intermediate

What is Spring Boot caching with @Cacheable?

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".