Java 如何使Spring@Cacheable在AspectJ方面之上工作?
我创建了一个AspectJ方面,它在spring应用程序中运行良好。现在我想添加缓存,使用springs可缓存注释 为了检查是否拾取了@Cacheable,我使用了一个不存在的缓存管理器的名称。常规运行时行为是引发异常。但在本例中,没有抛出异常,这表明@Cacheable注释没有应用于拦截对象Java 如何使Spring@Cacheable在AspectJ方面之上工作?,java,spring,aspectj,aspect,Java,Spring,Aspectj,Aspect,我创建了一个AspectJ方面,它在spring应用程序中运行良好。现在我想添加缓存,使用springs可缓存注释 为了检查是否拾取了@Cacheable,我使用了一个不存在的缓存管理器的名称。常规运行时行为是引发异常。但在本例中,没有抛出异常,这表明@Cacheable注释没有应用于拦截对象 /* { package, some more imports... } */ import org.aspectj.lang.ProceedingJoinPoint; import org.aspec
/* { 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;
}
}
鉴于我的方面已经在工作,我如何使@Cacheable在其之上工作?通过使用Spring常规依赖项注入机制,并将
org.springframework.cache.CacheManager
注入方面,您可以获得类似的结果:
@Autowired
CacheManager cacheManager;
然后,您可以在以下建议中使用缓存管理器:
@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();
}
}
我最终得到了类似的结果,但这并没有能够添加注释那么好,而且它可以正常工作。谢谢你的努力。