What is the role of @EnableCaching in Spring Boot?
Answer:
Explanation:
The @EnableCaching
annotation in Spring Boot is used to enable caching in the application. When you apply this annotation to a configuration class, it activates Spring’s annotation-driven cache management capability, allowing you to use caching annotations like @Cacheable
, @CachePut
, and @CacheEvict
to manage caching behavior at the method level.
Here’s an example of enabling caching in a Spring Boot application:
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableCaching
public class CacheConfig {
}
Once caching is enabled, you can use caching annotations on service methods to store and retrieve results from the cache:
@Service
public class MyService {
@Cacheable("myCache")
public String getData(String id) {
return someExpensiveOperation(id);
}
}
In this example, the @Cacheable
annotation tells Spring to check the cache before executing getData()
. If the result is in the cache, it’s returned directly; otherwise, the method is executed, and the result is stored in the cache for future use. This reduces the need to recompute or re-fetch data, improving application performance.