How to use @Cacheable in Spring?

In Spring, the @Cacheable annotation is used to cache the return value of a method. When the method is called again with the same arguments, the result is retrieved directly from the cache without re-executing the method.

To use the @Cacheable annotation, you need to follow the following steps:

  1. Enable caching using annotations.
  2. Make use of cache
  3. @Enable caching with the key based on the parameter.

For example, consider the UserService interface and its implementation class:

public interface UserService {
    User getUserById(long id);
}

@Service
public class UserServiceImpl implements UserService {

    @Override
    @Cacheable(value = "userCache", key = "#id")
    public User getUserById(long id) {
        // 从数据库中获取用户数据
        // ...
        return user;
    }
}

In the example mentioned above, the @Cacheable annotation is used on the getUserById() method, specifying the cache name as “userCache” and the cache key as the id parameter. When the getUserById() method is called, if the result with the specified key already exists in the cache, it is retrieved directly from the cache; otherwise, the method is executed and the result is stored in the cache.

It is important to note that in order for the @Cacheable annotation to work, you also need to configure a cache manager in the Spring configuration file, such as using SimpleCacheManager.

<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
    <property name="caches">
        <set>
            <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean" p:name="userCache"/>
        </set>
    </property>
</bean>

The above configuration creates a cache named “userCache” using ConcurrentMapCacheFactoryBean as the cache implementation. You can also use other cache implementations such as Ehcache, Redis, etc.

In this way, when the getUserById() method is called multiple times with the same id parameter, the return value will be directly retrieved from the cache instead of executing the method body again, improving system performance.

bannerAds