0 day streak
java / expert
Snippet

Runtime Cache Selection with Custom CacheResolver

While @Cacheable usually targets a static cache name, CacheResolver allows dynamic determination of the cache at runtime. This is critical for multi-tenant applications where each tenant must have isolated cache storage.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
public class TenantCacheResolver extends AbstractCacheResolver {
public TenantCacheResolver(CacheManager cacheManager) {
super(cacheManager);
}
@Override
protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) {
String tenantId = TenantContext.getTenantId();
return Collections.singletonList("cache_" + tenantId);
}
}
spring
Breakdown
1
extends AbstractCacheResolver
Inherits base functionality for resolving caches via a CacheManager.
2
getCacheNames(CacheOperationInvocationContext<?> context)
Exposes metadata about the method call (arguments, target) to decide which cache to use.
3
return Collections.singletonList("cache_" + tenantId);
Dynamically constructs the cache name based on the current execution context.