我创建了一个在 spring 应用程序中运行良好的 AspectJ 方面。现在我想添加缓存,使用springs Cacheable注解。
为了检查@Cacheable 是否被提取,我使用了一个不存在的缓存管理器的名称。常规的运行时行为是抛出异常。但在这种情况下,没有抛出异常,这表明 @Cacheable 注释没有应用于拦截对象。
/* { 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 常规依赖注入(inject)机制并将 org.springframework.cache.CacheManager
注入(inject)到您的方面来实现类似的结果:
@Autowired
CacheManager cacheManager;
然后你就可以在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();
}
}
关于java - 如何使 Spring @Cacheable 在 AspectJ 切面之上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39047520/