【问题标题】:@Cacheable with condition for method arguments@Cacheable 方法参数的条件
【发布时间】:2018-08-25 10:24:40
【问题描述】:

我从春天读到 @Cacheable docs (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){}

这是我的Request POJO:

public class Request{
 private String id;

 public String getId(){
  return this.id; 
 }

 public void setId(String id){
  this.id = id;
 }

}

但它因 Spring SpEL 异常而失败,说“!”是无效的。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: spring spring-data spring-el


    【解决方案1】:

    首先,变量(参数)是#req,所以你需要!#req...

    其次,您需要将myStr 表示为SpEL 中的文字字符串。

    把它们放在一起......

    @Cacheable(condition="!#req.id.equals('" + myStr + "')")
    

    (注意myStr 值周围的单引号)。

    【讨论】:

      【解决方案2】:

      据我了解,您不能先使用 # ,然后再按顺序使用其他运算符。 你必须使用像 - “#...等于(..)==假” 或者, "#...等于(..) != true"

      另外,最好按照 Gary Russell 第一个答案的建议使用。

      【讨论】:

      • 是的,你是对的。我的意思是,# 之后!操作员。谢谢
      猜你喜欢
      • 2012-12-13
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 2016-06-15
      • 2016-07-05
      • 2019-05-08
      • 1970-01-01
      • 2016-04-10
      相关资源
      最近更新 更多