Reputation: 1190
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
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:
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.
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