Disable spring caching method via external property

I configured spring caching method with ehcache configuration and annotation.

However, I would like to be able to disable it from the configuration file that we use in the application.

My first idea was to call net.sf.ehcache.CacheManager.CacheManager() with no arguments if method caching is disabled. This throws an exception:

 java.lang.IllegalArgumentException: loadCaches must not return an empty Collection at org.springframework.util.Assert.notEmpty(Assert.java:268) at org.springframework.cache.support.AbstractCacheManager.afterPropertiesSet(AbstractCacheManager.java:49) 

My second idea was to set net.sf.ehcache.CacheManager.CacheManager() to default data so that the cache would not be used (maxElementsInMemory 0, etc.). But then the cache is still in use, which I don’t want.

There is a net.sf.ehcache.disabled property, but I do not want to disable sleep caching, which also uses ehcache.

Q How do I configure everything to cache spring methods, but disable it from my external configuration file? I do not want to change the application context or code to enable / disable method caching. Only the configuration files that we use in the application can be changed.

+6
source share
2 answers

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; } 
+8
source

You can use spring profile to enable (or not) spring caching support

 <beans profile="withCache"> <cache:annotation-driven /> </beans> 
+3
source

All Articles