文章目录
- 1、获取@Cacheable注解的属性
- 2、获取自定义注解的属性
1、获取@Cacheable注解的属性
有个小需求,要在日志中打印支持redis缓存的方法的相关信息,这里切点表达式动词用@annotation,后面跟Cacheable注解
@Component
@Aspect
@Slf4j
public class RedisAdvice {@Pointcut("@annotation(org.springframework.cache.annotation.Cacheable)")public void redisCut(){}//Cacheable redisInfo,//redisInfo随便起的,但必须和下面doAround方法中的形参名一样@Around("redisCut() &&@annotation(redisInfo)")public Object doAround(ProceedingJoinPoint proceedingJoinPoint,Cacheable redisInfo) throws Throwable {//获取属性StringBuilder redisKey = new StringBuilder(redisInfo.key()).append("::").append(redisInfo.value()[0]);MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();String methodName = signature.getName();log.info("RdisInfo: key: {} ,methodName: {}",redisKey,methodName);Object ret = proceedingJoinPoint.proceed();return ret;}}
2、获取自定义注解的属性
自己定义个注解来搭配AOP获取一下,注解有三个属性,value,description和title
主要是为了某些切点有时候不能统一表达,那就可以直接自定义个注解,然后统一标记一下,也算是个实现思路吧。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {String value();String description() default "this is my annotation!";String title() default "";
}
在service层中的方法上使用这个自定义注解
@Service
public class MyService {@MyAnnotation("this is a value")public void methodOne(){System.out.println("MyService类中的methodOne方法");}@MyAnnotation(value = "methodTwo value",description = "MyService.method",title = "aop")public void methodTwo(){System.out.println("MyService类中的methodTwo方法");}
}
切面通知类里获取注解属性
@Component
@Aspect
public class CutAdvice {@Pointcut("@annotation(cn.itcast.user.annotation.MyAnnotation)")public void pointCut(){}@Before("pointCut() && @annotation(param)")public void beforeSome(MyAnnotation param){System.out.println("aop + annotation value: " + param.value());System.out.println("aop + annotation description: " + param.description());System.out.println("aop + annotation title: " + param.title());}
}
写个测试接口:
@RestController
@RequestMapping("/aop")
public class MyController {@AutowiredMyService myService;@GetMapping("/annotation")public void myAnnotation(){myService.methodTwo();myService.methodOne();}
}
效果:
总结: