I need to dynamically assign values of cacheResolver
for @Cacheable
in runtime because cacheResolver
has the same value for @Cacheable
in every method. Hence, I use Spring AOP to dynamically assign the value but then Spring does not recognize the newly added value for cacheResolver
.
Seems that AOP load @Cacheable
value at the beginning.
Anyone knows how to make it work?
My AOP code:
@Aspect
@Component
@Order(1)
public class CacheableAspect {
@Pointcut("@annotation(org.springframework.cache.annotation.Cacheable)")
public void cacheablePointCut() {}
@Before("cacheablePointCut()")
public void addCacheableResolver(JoinPoint joinPoint) {
Annotation cacheableAnnotation = getCacheableAnnotation(joinPoint);
Object handler = Proxy.getInvocationHandler(cacheableAnnotation);
Field f;
try {
f = handler.getClass().getDeclaredField("memberValues");
} catch (NoSuchFieldException | SecurityException e) {
throw new IllegalStateException(e);
}
f.setAccessible(true);
Map<String, Object> memberValues;
try {
memberValues = (Map<String, Object>) f.get(handler);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalStateException(e);
}
memberValues.put("cacheResolver", "cacheableResolver");
}
private Annotation getCacheableAnnotation(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
return method.getAnnotation(Cacheable.class);
}
}
My @Cacheable
code in which i want cacheResolver
is dynamically assigned a value:
@Cacheable(value = "test")
public int test() {
System.out.println("xxx");
return 10;
}