WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Framework · Advanced · question 50 of 100

How can you implement caching in a Spring application using Spring Cache abstraction?

📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

Caching is an essential feature of any application that aims to improve performance and reduce external dependencies. In a Spring application, we can implement caching using the Spring Cache abstraction. The Spring Cache abstraction provides a consistent way of working with different caching technologies like EhCache, Redis, and others.

Heres a step-by-step guide on how to implement Caching in a Spring application using Spring Cache abstraction:

Step 1: Add Spring Cache Dependencies Add the Spring Boot dependencies for the caching abstraction and for the caching provider which you want to use. For example, the following dependencies can be added to the ‘pom.xml‘ file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

Step 2: Add Cache Configuration Add a caching configuration class to the application. The configuration class must include the ‘@EnableCaching‘ annotation that enables caching support in the application. This class can also include specific configurations for the chosen caching provider.

@Configuration
@EnableCaching
public class CacheConfiguration {

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager() {
        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(RedisCacheConfiguration.defaultCacheConfig()
                        .entryTtl(Duration.ofMinutes(10)))
                .build();
        return cacheManager;
    }
}

In the above example, we create a RedisTemplate bean for Redis cache provider and define the RedisCacheManager. RedisCacheConfiguration is used to specify the cache expiry time.

Step 3: Use Spring Cache Abstraction Once the caching configuration setup is complete, you can start using the Spring Cache abstraction. You can annotate methods with the ‘@Cacheable‘, ‘@CachePut‘, and ‘@CacheEvict‘ annotations to take advantage of caching.

The ‘@Cacheable‘ annotation indicates that a method result is cached and retrieved from the cache if the same method is called again with the same parameters. If the method is called with a new parameter, the result is re-evaluated and cached.

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Cacheable(value = "users")
    public User getUserByEmail(String email) {
        return userRepository.findByEmail(email);
    }

}

In the above example, the ‘getUserByEmail‘ method result will be stored in a cache named ‘users‘.

The ‘@CachePut‘ annotation updates the cache with the resulting object of a method call. This annotation is useful when you need to update a cache entry without waiting for it to expire.

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @CachePut(value = "users", key = "#user.email")
    public User createUser(User user) {
        return userRepository.save(user);
    }

}

In the above example, the ‘createUser‘ method creates a new user record in the database, and its result is stored in the cache named ‘users‘.

The ‘@CacheEvict‘ annotation removes a cache entry when a method is called. This annotation typically used when you’re finalizing an operation that could leave data in the cache invalid or stale.

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @CacheEvict(value = "users", key = "#user.email")
    public void deleteUserByEmail(User user) {
        userRepository.delete(user);
    }

}

In the above example, the ‘deleteUserByEmail‘ method removes the user record from the database and its cache entry from a cache named ‘users‘.

Conclusion: Using Spring Cache Abstraction simplifies caching within a Spring application, providing a consistent way of working with different caching technologies. Caching can be implemented easily in a Spring application using the ‘@Cacheable‘, ‘@CachePut‘, and ‘@CacheEvict‘ annotations, as shown in the examples above.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Framework interview — then scores it.
📞 Practice Spring Framework — free 15 min
📕 Buy this interview preparation book: 100 Spring Framework questions & answers — PDF + EPUB for $5

All 100 Spring Framework questions · All topics