如何让Spring @Cacheable在AspectJ方面工作? [英] How to make Spring @Cacheable work on top of AspectJ aspect?

查看:690
本文介绍了如何让Spring @Cacheable在AspectJ方面工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个AspectJ方面,它在spring应用程序中运行良好。现在我想使用spring Cacheable注释添加缓存。

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

要检查@Cacheable是否被拾取,我使用的是不存在的缓存管理器的名称。常规运行时行为是抛出异常。但在这种情况下,没有抛出任何异常,这表明@Cacheable注释未应用于拦截对象。

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;
    }
}

鉴于我的Aspect已经工作,我怎么能让@Cacheable在它上面工作?

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

推荐答案

你可以通过使用Spring常规依赖注入机制并注入一个类似的结果 org.springframework.cache.CacheManager 进入您的方面:

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

这篇关于如何让Spring @Cacheable在AspectJ方面工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆