- 首先我们写个自定义的注解
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno {
//定义一个变量,可以接受参数
String value() default "";
}
- 写个controller实现注解
@RestController
public class TestAopAnno {
@RequestMapping("/helloAnno")
@MyAnno("注解的参数值")
public String helloAnno(){
System.out.println("helloAnno");
return "helloAnno";
}
}
- 编写aop实现
@Aspect
@Component
public class MyAopAnno {
@Pointcut("@annotation(com.tw.study.anno.MyAnno)")
public void loganno(){
}
@Around("loganno()")
public void A1(ProceedingJoinPoint pjp){
Object rtValue = null;
try {
MethodSignature signature = (MethodSignature)pjp.getSignature();
String name = signature.getName();
System.out.println(name);
Method method = signature.getMethod();
Object proceed = pjp.proceed();
System.out.println(proceed);
MyAnno myanno = method.getAnnotation(MyAnno.class);
System.out.println("注解的值===="+myanno.value());
} catch (Throwable throwable) {
System.out.println("通知类中的aroundAdvice方法执行了。。异常");
throwable.printStackTrace();
}finally {
System.out.println("通知类中的aroundAdvice方法执行了。。后置");
}
}
}
- 测试
请求地址
测试结果
可以看见,在测试中,我们获取了注解的参数值,利用这个,我们可以做一些日志操作的实现。