快速入门

首先创建一个aop包, 在里面再创建一个类放通知
然后就是写 切入点表达式 , 具体看我下面的操作就行了~
@Component 表示这个类由Spring管理
@Aspect 告诉Spring这是个切面

@Component
@Aspect
public class MyAdvice {

    @Pointcut("execution(void com.itheima.dao.BookDao.update())")
    private void pt(){}

    @Before("pt()")
    public void method(){
        System.out.println(System.currentTimeMillis());
    }
}

然后在 Spring核心配置类 中添加注解, 让Spring知道我用了注解进行aop开发

@Configuration
@ComponentScan("com.itheima")
@EnableAspectJAutoProxy
public class SpringConfig {

}

AOP环绕通知

  1. 首先和普通AOP一样, 添加Bean并标记为切面

    @Component
    @Aspect
  2. 需要通过 ProceedingJoinPoint pjp 调用原方法
    pjp.proceed() 获得原方法的返回值, 可以修改后再return回去

    @Component
    @Aspect
    public class MyAround {
    
     @Pointcut("execution(* com.itheima.dao.BookDao.select(..))")
     private void pc(){}
    
     @Around("pc()")
     public Object around(ProceedingJoinPoint pjp) throws Throwable {
         System.out.println("select running...");
         Integer proceed = (Integer) pjp.proceed();
         System.out.println("select exist...");
         return proceed + 566;
     }
    }

AOP通知获取参数

  1. 前置通知(Before Advice)
@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        System.out.println("Arguments: " + Arrays.toString(args));
    }
}

2.环绕通知(Around Advice)

ProceedingJoinPoint是JoinPoint的子类, 所以自带getArgs()方法

@Aspect
@Component
public class LoggingAspect {

    @Around("execution(* com.example.service.*.*(..))")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Method called with arguments: " + Arrays.toString(joinPoint.getArgs()));
        
        Object result;
        try {
            result = joinPoint.proceed();  // 执行目标方法
            System.out.println("Method returned value: " + result);
        } catch (Throwable throwable) {
            System.out.println("Method threw an exception: " + throwable);
            throw throwable;  // 重新抛出异常
        }
        
        return result;
    }
}

获取原方法的信息

Signature signature = pjp.getSignature();//pjp就是ProceedingJoinPoint
String name = signature.getName();