Francisco Lozano
Francisco Lozano

Reputation: 372

Spring 3.1 cache - how to use the returned value in the SpEL

I am trying to make an eviction of an entry in a Spring-managed cache (Spring 3.1 abstraction).

I need to refer to the returned value of the method in the SpEL of the "key" property in the annotation:

    /* (How to refer to the 'T' returned value in the "KEY_ID"?) */
@Caching(evict = { @CacheEvict(value = CACHE_BY_ID, key = KEY_ID) })
public T delete(AppID appID, UserID userID) throws UserNotFoundException {
    return inner.delete(appID, userID);
}

Is there any way to do this?

Upvotes: 3

Views: 5838

Answers (3)

Max O
Max O

Reputation: 11

As mentioned above and according to Table 29.1 of the Cache SpEL available metadata at at https://docs.spring.io/spring-framework/docs/4.0.x/spring-framework-reference/html/cache.html

it is possible to use #result in 'unless' expressions and 'cache evict' expressions only when beforeInvocation is false.

To confirm, I have recently used #result successfully in @CacheEvict.

Upvotes: 0

Matt Broekhuis
Matt Broekhuis

Reputation: 2075

try using #result in your SpEL

Upvotes: 3

sdouglass
sdouglass

Reputation: 2390

It doesn't seem like there is any way to reference the returned object:

http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/cache.html#cache-spel-context

But why do you need to do that? You can refer to the arguments in the @CacheEvict "key" value, e.g.:

@CacheEvict(value = CACHE_BY_ID, key = "#userID")
public T delete(AppID appID, UserID userID) throws UserNotFoundException {
...
}

More example code in response to response below about having to evict from multiple caches using multiple properties of a User object:

@Caching(evict = {
    @CacheEvict(value = CACHE_BY_ID, key = "#user.userID"),
    @CacheEvict(value = CACHE_BY_LOGIN_NAME, key = "#user.loginName")
    // etc.
})
public T delete(AppID appID, User user) throws UserNotFoundException {
...
}

Upvotes: 2

Related Questions