What is the role of @EnableCaching in Spring Boot?

What is the role of @EnableCaching in Spring Boot?

A) To enable the application to cache data automatically
B) To configure cache settings in application.properties
C) To activate caching for specific beans or methods
D) To enable caching for all beans in the application

Answer:

A) To enable the application to cache data automatically

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.

Reference links:

Spring Boot Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top