springboot实现对注解的切⾯案例
对注解实现切⾯案例:
(1)定义⼀个注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String getValues() default "test annotation";
}
@Target(ElementType.METHOD)
表⽰该注解作⽤在⽅法上(type表⽰类上,field表⽰成员变量上)
@Retention(RetentionPolicy.RUNTIME)
表⽰该注解的作⽤范围,由于需要在运⾏时能够识别到该注解,所以是RUNTIME(SOURCE表⽰源码层⾯上,即编译
成.class时看不见该注解,⽽CLASS可以,但是在运⾏时看不到)
(2)编写对注解的切⾯
(只是记录的执⾏时间和打印⽅法,可以实现其他逻辑)
@Aspect
@Component
@Slf4j
public class MyAspect {
// value也可以写成value = "(execution(* com.sj..*(..))) && @annotation(zkDistributeLock)"
springboot实现aop@Around(value = "@annotation(myAnnotation)", argNames = "proceedingJoinPoint, myAnnotation")
public Object processTest(ProceedingJoinPoint proceedingJoinPoint, MyAnnotation myAnnotation) throws Throwable {
long beginTime = System.currentTimeMillis();
// 获取⽅法参数
Object[] args = Args();
// 执⾏⽅法
Object res = proceedingJoinPoint.proceed(args);
long time = System.currentTimeMillis() - beginTime;
MethodSignature signature = (MethodSignature) Signature();
String className = Target().getClass().getName();
String methodName = Name();
log.info("注解上的值:{}", Values());
log.info("执⾏时间:{}", time);
log.info("执⾏类和⽅法:{} {}", className, methodName);
return res;
}
}
(3)测试
@GetMapping("/go")
@MyAnnotation(getValues = "success")
public String test1() {
return "hello world";
}
执⾏结果:
注解上的值:success
执⾏时间:8
执⾏类和⽅法:com.***.TestController test1
到此这篇关于springboot实现对注解的切⾯案例的⽂章就介绍到这了,更多相关springboot实现对注解的切⾯内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。