我有一个带有@Cacheable注释定义的spring bean注释
@Service
public class MyCacheableBeanImpl implements MyCacheableBean {
@Override
@Cacheable(value = "cachedData")
public List<Data> getData() { ... }
}
Run Code Online (Sandbox Code Playgroud)
我需要这个类能够禁用缓存并仅使用来自原始源的数据.这应该基于来自外部的一些事件发生.这是我的方法:
@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 …Run Code Online (Sandbox Code Playgroud) 我从 spring@Cacheable文档(https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html#condition--)中读取condition可以指定方法条件的内容使用 SpEL 的参数。
我一直在尝试同样的方法但失败了。这是我的方法:
public static final String myStr = "4";
@Cacheable(condition="#!req.id.equals("+myStr+")")
public Response myCall(Request req){}
Run Code Online (Sandbox Code Playgroud)
这是我的RequestPOJO:
public class Request{
private String id;
public String getId(){
return this.id;
}
public void setId(String id){
this.id = id;
}
}
Run Code Online (Sandbox Code Playgroud)
但它因 Spring SpEL 异常而失败,并显示“!” 是无效的。有人可以帮我解决这个问题吗?