@Cacheable Annotation in Spring

Spring provides a caching abstraction that allows you to easily cache the results of method calls by simply annotating the methods you want to cache with @Cacheable.

Here’s an example of how you might use the @Cacheable annotation to cache the results of a method:


@Service
public class MyService {

    @Cacheable("users")
    public User getUser(int id) {
        // code to retrieve user from the database
    }
}

In this example, the getUser method is annotated with @Cacheable("users"). This tells Spring to cache the results of the method call, using the cache named “users”. The next time the getUser method is called with the same arguments, the cached result will be returned instead of executing the method again.

To enable caching in your Spring Boot application, you need to include the spring-boot-starter-cache dependency in your project, and configure a cache manager. Here is an example of how you might configure the caching in a Spring Boot application:


@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("users");
    }
}

In this example, the cacheManager method is annotated with @Bean, which tells Spring to create and manage an instance of the ConcurrentMapCacheManager class. The ConcurrentMapCacheManager is a simple cache manager that stores cache data in memory using a ConcurrentMap. The @EnableCaching annotation is used to enable caching support in the application.

Leave a Reply

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