title: How to temporarily disable caching for Spring cache
body: <p>I have a spring bean annotated with <code>@Cacheable</code> annotations defined like so</p>
  
  <pre><code>@Service
  public class MyCacheableBeanImpl implements MyCacheableBean {
      @Override
      @Cacheable(value = "cachedData")
      public List&lt;Data&gt; getData() { ... }
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>@Service
  public class MyCacheableBeanImpl implements MyCacheableBean, ApplicationListener&lt;CacheSwitchEvent&gt; {
      //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&lt;Data&gt; 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;
      }
  
  }
  </code></pre>
  
  <p>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?</p>