There is a method annotated with @Cacheable that returns an object:
@Service
public class UserService {
@Cacheable("userData")
public UserData getUserData(String userName) {
UserData userData = new UserData();
userData.setGotFromCache(false);
return userData;
}
}
And the UserData object:
@Getter
@Setter
public class UserData {
private boolean gotFromCache;
}
How to detect whether method annotated @Cacheable was called or whether its output comes from cache?
The workaround is to inject CacheManager and detect it manually:
Cache cache = this.cacheManager.getCache("userData");
UserData userData = null;
String userName = "some user name";
if (cache != null) {
Object key = SimpleKeyGenerator.generateKey(userName);
userData = cache.get(key, UserData.class);
if (userData != null) {
userData.setGotFromCache(true);
} else {
userData = userService.getUserData(userName);
cache.put(key, userData);
}
} else {
userData = userService.getUserData(userName);
}
However, this code doesn't utilize @Cacheable annotation for the simplicity.
Is it possible to use @Cacheable and detect whether output comes from cache?