java - 如何使 Spring @Cacheable 在 AspectJ 切面之上工作?

标签 java spring aspectj aspect

我创建了一个在 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/

相关文章:

java - 如何使用定时器类

java - 为什么数组允许使用克隆方法?

spring - bean 范围的真实用例

java - 无法在 hibernate 映射中加载数据

java - 如何将执行切入点与第三方maven依赖一起使用?

java - 使用数组在 MySQL 中插入值

java - 我应该通过重新抛出错误来排除 catch 语句中的错误报告吗?

java - Quartz 和 Spring 的 NullPointerException

java - AspectJ 之前可以从方法返回吗?

spring-security - Spring Security和AOP问题