3.2 注解中的ProceedingJoinPoint和JoinPoint说明
1.pom.xml添加aop支持
org.springframework.boot
spring-boot-starter-aop
2. 创建自定义注解
@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface MyLog {
String value() default “”;
}
@Documented 注解: Documented 注解表明这个注解应该被 javadoc工具记录. 默认情况下,javadoc是不包括注解的.但如果声明注解时指定了 @Documented,则它会被 javadoc 之类的工具处理, 所以注解类型信息也会被包括在生成的文档中
@Inherited 注解: 它指明被注解的类会自动继承. 更具体地说,如果定义注解时使用了 @Inherited 标记
然后用定义的注解来标注另一个父类, 父类又有一个子类(subclass),则父类的所有属性将被继承到它的子类中
@Target(ElementType.TYPE) //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包
1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
3.Rete
【一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
ntionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.
@Component
@Aspect
public class LogAspect {
@Pointcut("@annotation(com.example.config.MyLog)")
private void cut() { }
@Around(“cut()”)
public void advice(ProceedingJoinPoint joinPoint){
System.out.println(“环绕通知之开始”);
try {
joinPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println(“环绕通知之结束”);
}
//当想获得注解里面的属性,可以直接注入改注解
@Before(“cut()&&@annotation(myLog)”)
public void record(JoinPoint joinPoint, MyLog myLog) {
System.out.println(myLog.value());
}
@After(“recordLog()”)
public void after() {
this.printLog(“已经记录下操作日志@After 方法执行后”);
}
}