windupurnomo
windupurnomo

Reputation: 1190

SpringBoot Cache, Call @Cacheable Method from @Cacheput Method not Work

If I call directly to @Cacheable (findById), it working well. But If I call from @Cacheput method, it's not work.

    @Cacheable(key = "#p0")
    public User findById(String userId) {
        User user = userRepository.findById(userId).orElseThrow(() -> new NotFoundException());
        return user;
    }
    @CachePut(key = "#p0")
    public User disabled(String userId) {
        User user = findById(userId);
        user.setStatus(0);
        userRepository.save(user);
        return user;
    }

Upvotes: 0

Views: 1694

Answers (1)

Tom Cools
Tom Cools

Reputation: 1138

"Does not work" is a bit abstract, so i'll assume you mean "the caching doesn't work and the method is called every time".

That is exactly the difference between the two:

  • @Cacheable: Method will only be called once and result will be put into the cache.
  • @CachePut: Cache will be updated, but the method will be called every time!

From the docs:

In contrast to the @Cacheable annotation, this (@CachePut) annotation does not cause the advised method to be skipped. Rather, it always causes the method to be invoked and its result to be stored in the associated cache. Note that Java8's Optional return types are automatically handled and its content is stored in the cache if present.

From: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/annotation/CachePut.html

To add to the problem, if you call another method internally (you call @Cachable from @Cacheput), the annotation won't work, because annotations in Spring usually only work when you call the method publicly (as in, from outside your class). Calling a method from inside the same class doesn't give the Spring framework the opportunity to get in between your code and do it's magic.

Upvotes: 1

Related Questions