我有一个 spring bean 注释为@Cacheable
像这样定义的注释
@Service
public class MyCacheableBeanImpl implements MyCacheableBean {
@Override
@Cacheable(value = "cachedData")
public List<Data> getData() { ... }
}
我需要此类能够禁用缓存并仅使用原始来源的数据。这应该基于外部的某些事件而发生。这是我的方法:
@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;
}
}
我担心的是这种方法的“魔力”程度非常高。我什至不确定如何测试这是否有效(根据 spring 文档,这应该有效,但如何确定)。我做对了吗?如果我错了那么如何纠正?
我正在寻找的是 NoOpCacheManager:
为了使它工作,我从 xml bean 创建切换到工厂
我做了如下事情:
@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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)