Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Cacheable with condition for method arguments

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?

like image 702
Manas Saxena Avatar asked Oct 25 '25 05:10

Manas Saxena


1 Answers

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).

like image 165
Gary Russell Avatar answered Oct 26 '25 20:10

Gary Russell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!