拦截org.springframework.cache.interceptor.CacheInterceptor#invoke的spring aop

尤慕李*_*尤慕李 4 java aop spring aspect spring-cache

我已经尝试了以下代码,但它不起作用:

@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();
    }
}
Run Code Online (Sandbox Code Playgroud)

PS我确定CacheInterceptor是弹簧管理的bean。

尤慕李*_*尤慕李 5

经过一些试验,我发现用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;
    }
  }
Run Code Online (Sandbox Code Playgroud)

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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

CacheInterceptorbean 中内置的 spring可以在ProxyCachingConfigurationclass 中找到。

希望能帮助到你。

  • 这个解决方案帮助我在我的自定义拦截器中使用缓存提供者 put 方法,这使我能够在 put 上设置驱逐时间,这不是 spring 缓存抽象的一部分 - 我在 cacheInterceptor() bean 方法上添加了@Primary,谢谢! (2认同)