package com.backendsys.modules.common.config.cache; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Component; import java.lang.reflect.Method; @Aspect @Component public class CacheAspect { @Around("@annotation(org.springframework.cache.annotation.Cacheable)") public Object logCacheableMethod(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); // 获取 @Cacheable 注解 Cacheable cacheable = method.getAnnotation(Cacheable.class); String cacheName = cacheable.value()[0]; // 获取缓存名称 String key = cacheable.key(); // 获取缓存键 // 获取方法参数 Object[] args = joinPoint.getArgs(); String keyExpression = key; if (keyExpression.contains("#")) { // 替换表达式中的参数占位符 for (int i = 0; i < args.length; i++) { keyExpression = keyExpression.replace("#" + signature.getParameterNames()[i], args[i].toString()); } } // 执行方法 Object result = joinPoint.proceed(); // 输出日志 System.out.println("记录缓存 (" + cacheName + "): { key: " + keyExpression + ", value: " + result + " }"); return result; } }