I have a spring bean annotated with @Cacheable
annotations defined like this
@Service public class MyCacheableBeanImpl implements MyCacheableBean { @Override @Cacheable(value = "cachedData") public List<Data> getData() { ... } }
I need this class so that it can turn off caching and only work with data from the original source. This should be based on some event from the outside. Here is 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 verify that this will work (based on spring documentation this should work, but how to be sure). Am I doing it right? If I am wrong, then how to do it right?
source share