2

I read from spring @Cacheable docs (https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html#condition--) that condition can specify conditions on method arguments using SpEL.

I have been trying the same out but failing. Here is my method:

public static final String myStr = "4";
@Cacheable(condition="#!req.id.equals("+myStr+")")
public Response myCall(Request req){}

and here is my Request POJO:

public class Request{
 private String id;

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

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

}

But it's failing with spring SpEL exceptions, saying that '!' is invalid. Can someone please help me out get the condition right?

Bonifacio2
  • 3,405
  • 6
  • 34
  • 54
Manas Saxena
  • 2,171
  • 6
  • 39
  • 58
  • Another approach using the `conditional` property [can be found here in this similar question](https://stackoverflow.com/a/74057340/26510) – Brad Parks Oct 13 '22 at 14:19

2 Answers2

6

First of all, the variable (argument) is #req, so you need !#req....

Second, you need to represent myStr as a literal String in SpEL.

Putting it all together...

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

(Note the single quotes around the value of myStr).

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
0

As per my understanding, you cannot use at first # and then other operator sequentially. You have to use like - "#...equals(..) == false" Or, "#...equals(..) != true"

Also, best to use as suggested by the first answer by Gary Russell.

Myth
  • 86
  • 2
  • 10