TheJeff
TheJeff

Reputation: 4101

CacheEvict on conditional annotation - Spring Caching

I have a weird case where my @CacheEvict is not working. Code looks like this:

@Caching(evict = {
        @CacheEvict(value = CacheConsts.C_CACHE1, keyGenerator = CacheConsts.KG_CACHE1, condition="#someModel != null && #someModel.getSomeProperty() != null"),
        @CacheEvict(value = CacheConsts.C_CACHE2, keyGenerator = CacheConsts.KG_CACHE2, condition="#someModel != null && #someModel.getSomeProperty() != null"),
        @CacheEvict(value = CacheConsts.C_CACHE3, keyGenerator = CacheConsts.KG_CACHE3, condition="#someModel != null && #someModel.getSomeProperty() != null")
})
public boolean addModel(ModelDTO someModel, String tenant);

However, it works when I remove the condition!!! Even though all data I test with is non-null.

Ex: when I remove this: "#someModel != null && #someModel.getSomeProperty() != null", it works.

I'm testing with a ModelDTO that is not null and the "someProperty" is not null either.

It seems to me that the condition would pass and it would evict.. but that is not what's happening.

Any ideas?

Is my Spel properly formed?

Why would my cache not evict here?

Does this have something to do with the @Caching annotation or some behavior of CacheEvict's condition that I'm unaware of?

Thanks for any help or ideas folks.

Upvotes: 2

Views: 4424

Answers (1)

John Blum
John Blum

Reputation: 7981

AFAICT, your SpEL expression and condition seem correct.

You might want to verify your compiler has debug set to true, which is required to reference method parameters by "name" since the compiler will then include variable names in the Java bytecode.

You might also try referring to method parameters in your SpEL expression, generically (for debugging purposes), such as: #a0 != null && #a0.someProperty(); refer to this section in the docs.

Finally, I have written a simple Integration Test simulating your UC above.

The test and supporting code (all contained in the referenced test class) are similar to an extent. However, my code is slightly different in that I am not using a custom KeyGenerator (per Cache), therefore I did not require the containing Caching annotation (I simply used cacheNames), but that should be of little consequence. The test passed!

Hopefully, this will give you more ideas.

Feel free to play around with my test to experiment as necessary.

Cheers!

Upvotes: 3

Related Questions