首页 文章

如何让Spring @Cacheable在AspectJ方面工作?

提问于
浏览
2

我创建了一个AspectJ方面,它在spring应用程序中运行良好 . 现在我想使用spring 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;
    }
}

鉴于我的Aspect已经开始工作,我怎样才能让@Cacheable工作呢?

1 回答

  • 1

    您可以通过使用Spring常规依赖项注入机制并在您的方面注入 org.springframework.cache.CacheManager 来实现类似的结果:

    @Autowired
    CacheManager cacheManager;
    

    然后你可以在around建议中使用缓存管理器:

    @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();
        }
    }
    

相关问题