Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register a custom CacheInterceptor instead of the one packaged in Spring?

We're working on a multitenant application, and we need that the @Cacheable with custom key take into account an additional parameter, the tenantId. Spring Cache allows to customize the keg generator, implementing the interface org.springframework.cache.interceptor.KeyGenerator

However that generator is not used by the Caching framework when the @Cacheable annotation is defined with a key (which indicates Spring Cache that they should not use the KeyGenerator, at least in Spring 3.2). This does not take into account the use case of multitenant applications, where all keys need to take into account the tenantId to avoid clashing keys between tenants.

A solution for this problem is to replace the CacheInterceptor that comes with Spring Cache, by a custom version that do use the KeyGenerator in any case.

The key part of code is in the superclass of CacheInterceptor, CacheAspectSupport:

/**
* Computes the key for the given caching operation.
* @return generated key (null if none can be generated)
*/
protected Object generateKey() {
    if (StringUtils.hasText(this.operation.getKey())) {
        return evaluator.key(this.operation.getKey(), this.method, this.evalContext);
        }
    return keyGenerator.generate(this.target, this.method, this.args);
}

We handle a way of replacing that code for a version that takes into account the generation independently of the value of

this.operation.getKey() 

by subclassing CacheInterceptor and overriding a couple of things. However, there is no easy way of replacing the interceptor in Spring Cache configuration. We're using xml configuration with

<cache:annotation-driven /> 

tags

The same question arisen in the Spring forums some time ago but there were no answers so far

like image 584
dds Avatar asked Nov 28 '25 14:11

dds


1 Answers

We found the answer looking into this other stackoverflow question that was meant to show how to replace the KeyGenerator. The key was to comment out the

<cache:annotation-driven /> 

from xml, and configure manually the interceptor for the annotations. It worked like a charm!

like image 96
dds Avatar answered Nov 30 '25 02:11

dds



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!