1
votes

Is it possible to use spring property placeholders in the unless expression of the @Cacheable annotation? I have a service method I would like cached unless the result returned is less than the value the property minCacheCalc specified in @PropertySource("classpath:application.properties").

Here is the service class method I want to cache:

@Service
class CalculationService {
    // @Cacheable(cacheNames="calculations", unless="#result < 10") // works fine hardcoded
    @Cacheable(cacheNames="calculations", unless="#result < ${minCacheCalc}")
    public Integer calculate(Integer i) {
        System.out.println("calculate(" + i + ")");
        return i * i - i;
    }

}

Calls to this throw the error:

SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

I have tried many variations of syntax but I can't seem to find one.

Is there a way to reference a property in my @Cacheable's unless parameter?

2
I've used @TomCollins ' workaround here: stackoverflow.com/a/34475679/973060. I am afraid my use case might not be supported. - Chris Everitt

2 Answers

0
votes

I think it should look more like:

#{result lt minCacheCalc}

I used this as a reference.

0
votes

You can achieve this like this :

  • Inject the property value in the field of the class
private int minCacheCalc;

public CalculationService(@Value("${minCacheCalc}") int minCacheCalc) {
    this.minCacheCalc = minCacheCalc;
}

  • Add a getter of the property
public int getMinCacheCalc() {
    return this.minCacheCalc;
}
  • Use the instance field in the unless SpEL
@Cacheable(cacheNames="calculations", unless="#result < #root.target.minCacheCalc")