Spring Cache 추상화 기초
@Cacheable, @CachePut 및 @CacheEvict를 사용해 비즈니스 로직을 수정하지 않고 캐싱을 추가합니다.
Spring Cache 추상화 기초은(는) CoddyKit의 무료 Spring Boot 4 Complete Guide 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Complete Guide 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why a Cache Abstraction?
Caching stores the result of an expensive operation so the next identical call returns instantly. The naive approach scatters if (map.containsKey(key)) ... logic across your service methods, mixing caching with business logic.
Spring's Cache Abstraction solves this. You declare caching with annotations, and Spring weaves the logic in via AOP proxies. Your method body stays focused on the actual work.
- @Cacheable — return cached value if present, else run the method and store the result
- @CachePut — always run the method, then update the cache
- @CacheEvict — remove entries from the cache
Enabling Caching
The abstraction is opt-in. Add @EnableCaching to a configuration class (or your main application class). This tells Spring to scan for caching annotations and create the proxies that intercept your method calls.
Without a CacheManager bean, Spring Boot auto-configures a simple in-memory ConcurrentMapCacheManager — fine for development, but you'll swap it for Caffeine or Redis in production.
@SpringBootApplication
@EnableCaching
public class StoreApplication {
public static void main(String[] args) {
SpringApplication.run(StoreApplication.class, args);
}
}@Cacheable in Action
@Cacheable is the workhorse. On the first call with a given argument, Spring runs the method and stores the result under a key. On subsequent calls with the same argument, the method body is skipped entirely and the cached value is returned.
The value (or cacheNames) attribute names the logical cache. The key defaults to the method arguments.
@Service
public class BookService {
@Cacheable("books")
public Book findByIsbn(String isbn) {
// Simulates a slow database lookup
simulateSlowService();
return new Book(isbn, "Spring in Action");
}
}How the Cache Key Is Built
By default the key is derived from the method parameters. With one parameter, that parameter is the key. With multiple parameters, Spring uses a SimpleKey combining them.
You can take control with a SpEL expression in the key attribute. This is essential when only part of an argument should form the key.
key = "#isbn"— use the isbn argumentkey = "#book.id"— use a property of the argumentkey = "#root.methodName + #id"— combine metadata and arguments
@Cacheable(cacheNames = "books", key = "#book.isbn")
public Book refresh(Book book) {
return reload(book);
}Conditional Caching
Sometimes you only want to cache certain results. Two SpEL attributes help:
- condition — evaluated before the method runs; caching applies only if it is true
- unless — evaluated after the method runs (it can see the result via
#result); it vetoes caching when true
A common pattern: never cache null results, so a failed lookup isn't remembered.
@Cacheable(
cacheNames = "books",
key = "#isbn",
condition = "#isbn.length() > 0",
unless = "#result == null")
public Book findByIsbn(String isbn) {
return repository.lookup(isbn);
}@CachePut: Always Run, Always Update
Unlike @Cacheable, @CachePut always executes the method and then stores the returned value into the cache. Use it for create/update operations where you want the fresh result to populate the cache.
Pin the key to the same value @Cacheable reads, so a later findByIsbn sees the updated entry instead of a stale one.
@CachePut(cacheNames = "books", key = "#result.isbn")
public Book updateBook(Book book) {
return repository.save(book);
}Cacheable vs CachePut — The Key Decision
It is tempting to put @Cacheable on an update method, but that is a bug: @Cacheable may skip the method entirely if the key already exists, so your save never runs.
- Read methods that should short-circuit on a hit → @Cacheable
- Write methods that must always execute, but should refresh the cache → @CachePut
Never put both on the same method — their semantics conflict (one may skip, the other always runs).
@CacheEvict: Removing Entries
@CacheEvict removes data from the cache, typically on delete or when an entry becomes invalid. Target a single key, or wipe the whole cache with allEntries = true.
By default eviction happens after the method returns successfully. Set beforeInvocation = true to evict even if the method throws.
@CacheEvict(cacheNames = "books", key = "#isbn")
public void deleteBook(String isbn) {
repository.delete(isbn);
}
@CacheEvict(cacheNames = "books", allEntries = true)
public void reloadCatalog() {
repository.reloadAll();
}Composing Multiple Operations with @Caching
When one method needs several caching operations — for example updating one cache while evicting from another — use @Caching to group them. It accepts arrays of cacheable, put, and evict annotations.
This avoids the limitation that you cannot repeat the same annotation type directly on a method (in older Java) and keeps related operations together.
@Caching(
put = { @CachePut(cacheNames = "booksById", key = "#book.id") },
evict = { @CacheEvict(cacheNames = "bookSearch", allEntries = true) })
public Book save(Book book) {
return repository.save(book);
}The Self-Invocation Trap
Spring's caching works through a proxy that wraps your bean. The annotation only fires when the call enters the bean from outside. If a method calls another cached method on this, the call bypasses the proxy and caching is silently skipped.
- Move the cached method to a separate bean, or
- Inject a self-reference, or use
AopContext.currentProxy()
This is the same proxy limitation you see with @Transactional.
@Service
public class CatalogService {
public List<Book> report() {
// BUG: internal call -> proxy bypassed, NOT cached
return List.of(findByIsbn("123"));
}
@Cacheable("books")
public Book findByIsbn(String isbn) {
return repository.lookup(isbn);
}
}A Tiny Standalone Cache Demo
To see the caching concept without Spring, here is a plain Java program that memoizes results in a Map — exactly what @Cacheable automates for you. Run it and notice the second call is instant because it hits the cache.
import java.util.HashMap;
import java.util.Map;
public class Main {
static Map<String, String> cache = new HashMap<>();
static String findByIsbn(String isbn) {
if (cache.containsKey(isbn)) {
return cache.get(isbn) + " (from cache)";
}
try { Thread.sleep(200); } catch (InterruptedException e) {}
String book = "Book-" + isbn;
cache.put(isbn, book);
return book + " (computed)";
}
public static void main(String[] args) {
System.out.println(findByIsbn("123"));
System.out.println(findByIsbn("123"));
}
}Quick Check
You have an updateBook(Book book) method that must always persist the book to the database and refresh the cache so later reads see the new data. Which annotation is correct?
Recap
You learned the Spring Cache Abstraction and its three core annotations:
- @EnableCaching turns the feature on; a
CacheManager(default in-memory, later Caffeine/Redis) backs it. - @Cacheable short-circuits on a hit — ideal for reads. Tune it with
key,condition, andunless. - @CachePut always runs then updates the cache — ideal for writes.
- @CacheEvict removes entries (one key or
allEntries), optionallybeforeInvocation. - Group operations with @Caching, and beware the self-invocation proxy trap.
The result: caching declared declaratively, with business logic untouched.
자주 묻는 질문
“Spring Cache 추상화 기초” 강의는 무료인가요?
네 — “Spring Cache 추상화 기초” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Complete Guide 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Complete Guide 강의에는 총 4개의 강의가 포함되어 있습니다.
“Spring Cache 추상화 기초”에서 뭘 배우나요?
@Cacheable, @CachePut 및 @CacheEvict를 사용해 비즈니스 로직을 수정하지 않고 캐싱을 추가합니다. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Complete Guide을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Spring Boot 4 Complete Guide을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Complete Guide은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“Spring Cache 추상화 기초” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Spring Boot 4 Complete Guide 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Spring Boot 4 Complete Guide 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Spring Cache 추상화 기초
- Caffeine 조정을 활용한 메모리 내 캐싱
- Redis와 TTL을 활용한 분산 캐싱
- 캐시 쇄도, 무효화 및 일관성