I have a spring bean annotated with @Cacheable
annotations defined like so
@Service
public class MyCacheableBeanImpl implements MyCacheableBean {
@Override
@Cacheable(value = "cachedData")
public List<Data> getData() { ... }
}
I need this class to be capable of disabling caching and working only with data from original source. This should happen based on some event from the outside. Here's my approach to this:
@Service
public class MyCacheableBeanImpl implements MyCacheableBean, ApplicationListener<CacheSwitchEvent> {
//Field with public getter to use it in Cacheable condition expression
private boolean cacheEnabled = true;
@Override
@Cacheable(value = "cachedData", condition = "#root.target.cacheEnabled") //exression to check whether we want to use cache or not
public List<Data> getData() { ... }
@Override
public void onApplicationEvent(CacheSwitchEvent event) {
// Updating field from application event. Very schematically just to give you the idea
this.cacheEnabled = event.isCacheEnabled();
}
public boolean isCacheEnabled() {
return cacheEnabled;
}
}
My concern is that the level of "magic" in this approach is very high. I'm not even sure how I can test that this would work (based on spring documentation this should work but how to be sure). Am I doing it right? If I'm wrong then how to make it right?