Sobes.tech
Junior — Middle

What annotation is used for integrating caching into a project?

sobes.tech AI

Answer from AI

In Java projects, the @Cacheable annotation from Spring Framework is often used for caching integration. It is applied to methods whose results need to be cached. On the first call, the method executes, and the result is stored in the cache. On subsequent calls with the same parameters, the result is retrieved from the cache, which improves performance.

Example of usage:

import org.springframework.cache.annotation.Cacheable;

public class UserService {

    @Cacheable("users")
    public User getUserById(Long id) {
        // Expensive operation, e.g., database query
        return userRepository.findById(id);
    }
}

Here, "users" is the cache name. Spring automatically manages storing and retrieving data from the cache.