'How to create custom Cache in Spring AOP
I am new to Spring AOP, and was reading how to create annotations.
I want to create a custom cache handler which would create a Cache for the particular request only.
I can inherit from HandlerInterceptorAdapter to create and clear the in memory cache.
and can use a ContextHolder for to store.
like
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class CachedContextHolder {
private static final ThreadLocal<GenericContext> CONTEXT_HOLDER = new ThreadLocal<>();
@Data
public static class GenericContext {
private AppEventHandlerPayload payload = new AppEventHandlerPayload();
private HashMap<String, Object> cache = new HashMap<String, Object>;
}
and store data in this particular context.
What I want to do is create a @cacheable annotation where I can intercept the method and if its available in cache return from there otherwise read from DB.
I was reading this https://www.baeldung.com/spring-aop-annotation
But not sure how to do this?
joinPoint.proceed();would execute the method but how do I get the params? couldnt see any methods here https://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/JoinPoint.html
I am new to Spring AOP, and couldn't find a proper fleshed out example anywhere. Any help would be great.
Solution 1:[1]
If you want to get the arguments you can use joinPoint.getArgs() https://www.eclipse.org/aspectj/doc/released/runtime-api/org/aspectj/lang/JoinPoint.html#getArgs().
Instead of creating your own implementation, I recommend using The Cache Abstraction from Spring: https://docs.spring.io/spring-framework/docs/current/reference/html/integration.html#cache and a cache provider like Caffeine or EhCache.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex |
