[Java2023] Day13.6,10-AOP的通知,切入点,连接点(概念)

54 阅读1分钟

一.通知

    1. 看起来就像Vue的生命周期函数

image.png

image.png

  • 2.通知顺序 由类名决定, 也可以给@Order(1),排序

image.png

二.切入点表达式(了解)

先了解, 用到时候再查; 感觉就是一个正则表达式一样, 用于匹配你要切入哪些方法(请求等)

image.png

image.png

image.png

  • 5.2@annotation根据注解匹配切入点 image.png

三.连接点(JoinPoint)

可以被AOP控制的方法, 被称为连接点

package com.tlias.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.util.Arrays;
//切面类
@Slf4j
@Aspect
@Component
public class MyAspect8 {
    @Pointcut("execution(* com.tlias.service.DeptService.*(..))")
    private void pt(){}
    @Before("pt()")
    public void before(JoinPoint joinPoint){
        log.info("MyAspect8 ... before ...");
    }
    @Around("pt()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("MyAspect8 around before ...");
        //1. 获取 目标对象的类名 .
        String className = joinPoint.getTarget().getClass().getName();
        log.info("目标对象的类名:{}", className);
        //2. 获取 目标方法的方法名 .
        String methodName = joinPoint.getSignature().getName();
        log.info("目标方法的方法名: {}",methodName);
        //3. 获取 目标方法运行时传入的参数 .
        Object[] args = joinPoint.getArgs();
        log.info("目标方法运行时传入的参数: {}", Arrays.toString(args));
        //4. 放行 目标方法执行 .
        Object result = joinPoint.proceed();
        //5. 获取 目标方法运行的返回值 .
        log.info("目标方法运行的返回值: {}",result);
        log.info("MyAspect8 around after ...");
        return result;
    }
}