How to make Spring @Cacheable work on top of AspectJ aspect?

限于喜欢 提交于 2019-12-19 09:26:11

问题


I created an AspectJ aspect which runs fine within a spring application. Now I want to add caching, using springs Cacheable annotation.

To check that @Cacheable gets picked up, I'm using the name of a non-existing cache manager. The regular run-time behavior is that an exception is thrown. But in this case, no exception is being thrown, which suggests that the @Cacheable annotation isn't being applied to the intercepting object.

/* { package, some more imports... } */

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.cache.annotation.Cacheable;

@Aspect
public class GetPropertyInterceptor
{
    @Around( "call(* *.getProperty(..))" )
    @Cacheable( cacheManager = "nonExistingCacheManager", value = "thisShouldBlowUp", key = "#nosuchkey" )
    public Object intercepting( ProceedingJoinPoint pjp ) throws Throwable
    {
        Object o;
        /* { modify o } */
        return o;
    }
}

Given that my Aspect is working already, how can I make @Cacheable work on top of it?


回答1:


You can achieve similar results, by using Spring regular dependency injection mechanism and inject a org.springframework.cache.CacheManager into your aspect:

@Autowired
CacheManager cacheManager;

Then you can use the cache manager in the around advice:

@Around( "call(* *.getProperty(..))" )
public Object intercepting( ProceedingJoinPoint pjp ) throws Throwable
{
    Cache cache = cacheManager.getCache("aopCache");
    String key = "whatEverKeyYouGenerateFromPjp";
    Cache.ValueWrapper valueWrapper = cache.get(key);
    if (valueWrapper == null) {
        Object o;
        /* { modify o } */
        cache.put(key, o); 
        return o;
    }
    else {
        return valueWrapper.get();
    }
}


来源:https://stackoverflow.com/questions/39047520/how-to-make-spring-cacheable-work-on-top-of-aspectj-aspect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!