什么是AOP

Aspect Oriented Programming(面向切面编程、面向方面编程),可简单理解为就是面向特定方法编程。

优点 :

  1. 减少重复代码
  2. 代码无侵入
  3. 提高开发效率
  4. 维护方便

导入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

核心概念


通知类型


通知顺序

当有多个切面的切入点都匹配到了目标方法,目标方法运行时,多个通知方法都会被执行。

执行顺序:


切入点表达式

1. execution:

2. @annotation

@Target(ElementType.METHOD) // 此注解可用于方法
@Retention(RetentionPolicy.RUNTIME) // 在运行时保留此注解
public @interface LogOperation {
}
@Before("@annotation(com.itheima.anno.LogOperation)")
public void before(){
    log.info("MyAspect -> before ...");
}
@LogOperation
@Override
public void delete(Integer id) {
    deptMapper.delete(id);
}

3, @pointcut切入点

@Pointcut( 切入点表达式)
public void pt(){}

Joinpoint连接点

@Around("execution(* com.itheima.service.DeptService.*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    String className = joinPoint.getTarget().getClass().getName(); // 获取目标类名
    Signature signature = joinPoint.getSignature(); // 获取目标方法签名
    String methodName = joinPoint.getSign
    Object[] args = joinPoint.getArgs(); 
    Object res = joinPoint.proceed(); // 
    return res;
}
@Before("execution(* com.itheima.service.DeptService.*(..))")
public void before(JoinPoint joinPoint) {
    String className = joinPoint.getTarget().getClass().getName(); // 获取目标类名

    Signature signature = joinPoint.getSignature(); // 获取目标方法签名
    String methodName = joinPoint.getSignature().getName(); // 获取目标方法名

    Object[] args = joinPoint.getArgs(); // 获取目标方法运行参数
}