CacheManager. getCache Always Return Null but the Value Is in cacheManager Bean When Inspect the Object

I'm trying to use Spring Cache to store data, generated by another method inside Service class.

This method marked with @Cacheable is a public method, the cache is being called in Controller layer.

When I do debugging, I inspect the object cacheManager, I found that it contains the map that I stored, but when calling the method cacheManager.getCache("cache") it return null.

Question is why that method return null while the object is holding the value?

This is the config, service and controller: Spring bean config:

@EnableCaching
public class CachingConfig {

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

Service:

public void verify(Request request, String authorization) {
        String memberId = parseAuthToken(authorization).getMembershipID();
        buildOtpCache(memberId, request.getTokenUUID(), 0)
    }

    @Cacheable("otpCache")
    public OTPCache buildOtpCache(String memberId, String uuid, int counter) {
        return OTPCache.builder()
            .memberId(memberId)
            .tokenUUID(uuid)
            .timestamp(LocalDateTime.now())
            .counter(counter)
            .build();
    }

Controller:

@Override
    public void verifyOTP(MeOTPVerifyRequest verifyOTPRequest, String authorization) {
        String memberId = parseAuthToken(authorization).getMembershipID();
        Collection<String> a = cacheManager.getCacheNames();
        OTPCache OTPCache = cacheManager.getCache("cache").get(memberId, OTPCache.class);
        otpService.verify(verifyOTPRequest, authorization);
    }

EDIT:

This is my new service class, remove @Cacheable annotation:

public void verify(Request request, String authorization) {
        String memberId = parseAuthToken(authorization).getMembershipID();
        cacheManager.getCache("optCache").put(memberId, buildOtpCache(memberId, request.getTokenUUID(), 0));
    }

    public OTPCache buildOtpCache(String memberId, String uuid, int counter) {
        return OTPCache.builder()
            .memberId(memberId)
            .tokenUUID(uuid)
            .timestamp(LocalDateTime.now())
            .counter(counter)
            .build();
    }
3
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article