spring expression with ResponseEntity Type

Actually, I am caching an Http Response using Spring Cache and now I want to put a condition that is to update the cache only when the Response is valid.

@Cacheable(value = CACHE, condition = "#result.body.responseData.toLowerCase().contains("A")")
public ResponseEntity<ProcessMqReqPostResponseBody> sendMqRequest(Integer pageNumber, Integer pageSize, String sortOrder, String merchantId) {
//Method Implementation
}

Without the condition, I can test my cache fine but when I added this condition, I get the error

org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field ‘body’ cannot be found on null

I don’t understand that because I can output the responseEntity in my test and it is not null. Is that behavior correct?

Thanks, Ashley

Answer

Spring’s behavior is correct because you are writing a condition that will work according to the result.

The #result value is always null before the method is executed, the result value is only filled after the method is executed.

If you want to test this, you can change your condition as follows, method will not be cached at all and will not give an error.

@Cacheable(value = CACHE, condition = "#result != null and #result.body.responseData.toLowerCase().contains("A")")

If you want to act on the result, you can only do so using the unless element.

Unlike condition(), this expression is evaluated after the method has been called and can therefore refer to the result.

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html#unless–

Leave a Reply

Your email address will not be published. Required fields are marked *