我创建了一个在spring应用程序中运行良好的AspectJ方面。现在,我想添加缓存,使用springs可缓存注释。
为了检查@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工作在它上面呢?
发布于 2016-08-19 22:21:09
您可以通过使用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();
}
}
https://stackoverflow.com/questions/39047520
复制相似问题