Spring AOP拦截org.springframework.cache.interceptor.CacheInterceptor#invoke方法

5
我尝试了以下代码,但它并没有起作用:
@Component
@Aspect
@Order(Integer.MAX_VALUE)
public class CacheAspect {

    @Around("execution(public * org.springframework.cache.interceptor.CacheInterceptor.invoke(..))")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //CLASS_CACHE.set(signature.getReturnType());
        return joinPoint.proceed();
    }
}

附言:我确定CacheInterceptor是一个由Spring管理的bean。


1
什么意思是“不起作用”? - Jens
@Jens CacheInterceptor#invoke 无法被拦截。 - 尤慕李
你为什么想要拦截和拦截器?! - M. Deinum
@M.Deinum 我想将方法信息收集到ThreadLocal中,并在其他地方使用它。 - 尤慕李
但是你真的想要拦截拦截器吗? - M. Deinum
如果您想收集缓存统计信息,有一种更简单的方法可以实现。据我所知,您无法拦截拦截器。 - Stephane Nicoll
1个回答

7

经过一些实验,我发现用用户自定义的弹簧替换内置的CacheInterceptor可以解决我的问题。以下是代码,以防有人有类似的需求。

  @Configuration
  @EnableCaching
  @Profile("test")
  public class CacheConfig {
    @Bean
    @Autowired
    public CacheManager cacheManager(RedisClientTemplate redisClientTemplate) {
      return new ConcurrentMapCacheManager(redisClientTemplate, "test");
    }

    @Bean
    public CacheOperationSource cacheOperationSource() {
      return new AnnotationCacheOperationSource();
    }

    @Bean
    public CacheInterceptor cacheInterceptor() {
      CacheInterceptor interceptor = new MyCacheInterceptor();
      interceptor.setCacheOperationSources(cacheOperationSource());
      return interceptor;
    }
  }

MyCacheInterceptor.java与CacheAspect共享相同的逻辑:

  public class MyCacheInterceptor extends CacheInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
      Method method = invocation.getMethod();
      //CLASS_CACHE.set(signature.getReturnType());
      return super.invoke(invocation);
    }
  }

CacheInterceptor bean中的Spring可以在ProxyCachingConfiguration类中找到。

希望对您有所帮助。


3
这个解决方案帮助我在自定义拦截器中使用缓存提供程序的put方法,使我能够在放置时设置过期时间,这不是Spring缓存抽象的一部分。我在cacheInterceptor() bean方法上添加了@Primary注释,谢谢! - lukass77

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接