How to temporarily disable caching for Spring Cache

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?

+5
source share
1 answer

What I was looking for was NoOpCacheManager:

To do this, I switched from creating an xml bean to a factory

I did something like the following:

  @Bean public CacheManager cacheManager() { final CacheManager cacheManager; if (this.methodCacheManager != null) { final EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager(); ehCacheCacheManager.setCacheManager(this.methodCacheManager); cacheManager = ehCacheCacheManager; } else { cacheManager = new NoOpCacheManager(); } return cacheManager; } 
+3
source

Source: https://habr.com/ru/post/1244801/


All Articles