Spring Boot FAQ: Top Questions
39. How does caching work in Spring Boot?
Spring Boot supports caching abstraction which can be backed by various providers like EhCache, Redis, or simple memory cache.
πΊοΈ Setup:
- Enable caching using
@EnableCaching
. - Use
@Cacheable
,@CachePut
,@CacheEvict
annotations.
π₯ Example:
@Cacheable("books")
public Book findBookById(String id) {
simulateSlowService();
return bookRepository.findById(id);
}
π Expected Output:
Subsequent calls return cached data without delay.
π οΈ Use Cases:
- Improving performance by reducing repeated calls.
- Caching frequently accessed data like product lists or settings.