文章目录
- 一、概念
- 1、定义
- 2、作用
 
- 二、Spring AOP
- 1、AOP 组成
- ① 切面(Aspect)
- ② 连接点(Join Point)
- ③ 切点(Pointcut)
- ④ 通知(Advice)
 
- 2、实现
- ① 添加 AOP 框架支持
- ② 定义切面和切点
- Ⅰ. 切点表达式
 
- ③ 定义相关通知
 
- 3、原理
- ① 织入(Weaving):代理的生成时机
- ② 动态代理
- ③ JDK 动态代理实现
- ④ CGLIB 动态代理实现
- ⑤ JDK 和 CGLIB 实现的区别
 
 
一、概念
1、定义
AOP(Aspect Oriented Programming):⾯向切⾯编程,它是⼀种思想,它是对某⼀类事情的集中处理。AOP 可以说是 OOP(Object Oriented Programming,⾯向对象编程)的补充和完善。
最常见的就是在登录页面进行登录校验,最初,我们需要在每个需要的地方实现验证方法;之后,我们可以写好调用方法,在需要的地方调用即可;学习 AOP 之后,我们只需要在某一处配置好,所有的登录界面就全部可以实现登录验证了。
2、作用
使⽤ AOP 可以扩充多个对象的某个能⼒,使用 AOP 可以实现:
- 统⼀的⽤户登录判断
- 统⼀⽇志记录
- 统⼀⽅法执⾏时间统计
- 统⼀的返回格式设置
- 统⼀的异常处理
- 事务的开启和提交等
二、Spring AOP
1、AOP 组成
① 切面(Aspect)
切⾯(Aspect)由切点(Pointcut)和通知(Advice)组成,它既包含了横切逻辑的定义,也包括了连接点的定义。
切⾯:定义 AOP 服务类型(干什么的)
② 连接点(Join Point)
应⽤执⾏过程中能够插⼊切⾯的⼀个点,这个点可以是⽅法调⽤时,抛出异常时,甚⾄修改字段时。切⾯代码可以利⽤这些点插⼊到应⽤的正常流程之中,并添加新的⾏为。
连接点:有可能调用 AOP 的地方。
③ 切点(Pointcut)
Pointcut 的作⽤就是提供⼀组规则(使⽤ AspectJ pointcut expression language 来描述)来匹配 Join Point,给满⾜规则的 Join Point 添加 Advice。
切点:定义 AOP 拦截规则。
④ 通知(Advice)
通知:定义了切⾯是什么,何时使⽤,其描述了切⾯要完成的⼯作,还解决何时执⾏这个⼯作的问题。
通知的分类:
- 前置通知使⽤ @Before:通知⽅法会在⽬标⽅法调⽤之前执⾏。
- 后置通知使⽤ @After:通知⽅法会在⽬标⽅法返回或者抛出异常后调⽤。
- 返回之后通知使⽤ @AfterReturning:通知⽅法会在⽬标⽅法返回后调⽤。
- 抛异常后通知使⽤ @AfterThrowing:通知⽅法会在⽬标⽅法抛出异常后调⽤。
- 环绕通知使⽤ @Around:通知包裹了被通知的⽅法,在被通知的⽅法通知之前和调⽤之后执⾏⾃定义的⾏为。
2、实现
Spring AOP 的实现步骤如下:
- 添加 Spring AOP 框架⽀持。
- 定义切⾯和切点。
- 定义通知
① 添加 AOP 框架支持
在 pom.xml 中增加 AOP 框架支持:
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
② 定义切面和切点
package com.example.mybatisdemo.aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
 * 登录的 AOP 实现代码
 */
@Component
@Aspect // 表示当前类为一个切面
public class LoginAOP {
	// 定义切点
    @Pointcut("execution(* com.example.mybatisdemo.controller.UserInfoController.*(..))")
    public void pointcut(){
        
    }
}

 其中 pointcut ⽅法为空⽅法,它不需要有⽅法体,此⽅法名就是起到⼀个“标识”的作⽤。
Ⅰ. 切点表达式
这⾥使⽤ AspectJ 表达式语法。
execution(<修饰符><返回类型><包.类.⽅法(参数)><异常>)
修饰符:一般省略
| 使用方法 | 意义 | 
|---|---|
| public | 公共方法 | 
| * | 任意 | 
返回值:不能省略
| 使用方法 | 意义 | 
|---|---|
| void | 没有返回值 | 
| String | 返回值字符串 | 
| * | 任意 | 
包
| 使用方法 | 意义 | 
|---|---|
| com.example.demo | 固定包 | 
| com.example.demo.*.service | demo包下面子包任意(com.example.demo.aaa.service) | 
| com.example.demo… | demo包下面的所有子包 | 
| com.example.demo.*.service… | demo包下面任意子包,固定目录service,service目录任意包 | 
类
| 使用方法 | 意义 | 
|---|---|
| UserInfoController | 指定类 | 
| User* | 以User开头 | 
| *Controller | 以Controller结尾 | 
| * | 任意 | 
方法名
| 使用方法 | 意义 | 
|---|---|
| sayhi | 固定方法 | 
| say* | 以say开头 | 
| *hi | 以hi结尾 | 
| * | 任意 | 
参数
| 使用方法 | 意义 | 
|---|---|
| () | 无参 | 
| (int) | 一个整型 | 
| (int ,int) | 两个整型 | 
| (…) | 任意参数 | 
③ 定义相关通知
package com.example.mybatisdemo.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
 * 登录的 AOP 实现代码
 */
@Component
@Aspect // 表示当前类为一个切面
public class LoginAOP {
    // 定义切点
    @Pointcut("execution(* com.example.mybatisdemo.controller.UserInfoController.*(..))")
    public void pointcut() {
    }
    /**
     * 前置通知
     */
    @Before("pointcut()")
    public void doBefore() {
        System.out.println("执行了前置通知!");
    }
    /**
     * 后置通知
     */
    @After("pointcut()")
    public void doAfter() {
        System.out.println("执行了后置通知!");
    }
    /**
     * return 之前通知
     */
    @AfterReturning("pointcut()")
    public void doAfterReturning() {
        System.out.println("执⾏了返回之后通知!");
    }
    /**
     * 抛出异常之前通知
     */
    @AfterThrowing("pointcut()")
    public void doAfterThrowing() {
        System.out.println("执⾏了抛异常后通知!");
    }
    /**
     * 环绕通知
     */
    @Around("pointcut()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        Object result = null;
        // 前置业务代码
        System.out.println("环绕通知的前置执行方法!");
        try {
            // 执行目标方法
            result = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        // 后置业务代码
        System.out.println("环绕通知的后置执行方法!");
        return result;
    }
}
在 postman 或者浏览器上访问 UserInfoController 中的接口,结果如下:
 
3、原理
Spring AOP 是构建在动态代理基础上,因此 Spring 对 AOP 的⽀持局限于方法级别的拦截。
Spring AOP ⽀持 JDK Proxy 和 CGLIB 方式实现动态代理。默认情况下,实现了接⼝的类,使用 AOP 会基于 JDK 生成代理类,没有实现接⼝的类,会基于 CGLIB ⽣成代理类。
① 织入(Weaving):代理的生成时机
织入:把切面应用到目标对象并创建新的代理对象。(生成代理)
织入共有三种时机:
- 编译期
- 类加载期
- 运⾏期
② 动态代理
此种实现在设计模式上称为动态代理模式,在实现的技术⼿段上,都是在 class 代码运⾏期,动态的织⼊字节码。
我们学习 Spring 框架中的AOP,主要基于两种⽅式:JDK 及 CGLIB 的⽅式。这两种⽅式的代理⽬标都是被代理类中的⽅法,在运⾏期,动态的织⼊字节码⽣成代理类。
③ JDK 动态代理实现
import org.example.demo.service.AliPayService;
import org.example.demo.service.PayService;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//动态代理:使⽤JDK提供的api(InvocationHandler、Proxy实现),此种⽅式实现,要求被代理类必须实现接⼝
public class PayServiceJDKInvocationHandler implements InvocationHandler {
    //⽬标对象即就是被代理对象
    private Object target;
    public PayServiceJDKInvocationHandler(Object target) {
        this.target = target;
    }
    //proxy代理对象
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
        //1.安全检查
        System.out.println("安全检查");
        //2.记录⽇志
        System.out.println("记录⽇志");
        //3.时间统计开始
        System.out.println("记录开始时间");
        //通过反射调⽤被代理类的⽅法
        Object retVal = method.invoke(target, args);
        //4.时间统计结束
        System.out.println("记录结束时间");
        return retVal;
    }
    public static void main(String[] args) {
        PayService target = new AliPayService();
        //⽅法调⽤处理器
        InvocationHandler handler =
                new PayServiceJDKInvocationHandler(target);
        //创建⼀个代理类:通过被代理类、被代理实现的接⼝、⽅法调⽤处理器来创建
        PayService proxy = (PayService) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                new Class[]{PayService.class},
                handler
        );
        proxy.pay();
    }
}
④ CGLIB 动态代理实现
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.example.demo.service.AliPayService;
import org.example.demo.service.PayService;
import java.lang.reflect.Method;
public class PayServiceCGLIBInterceptor implements MethodInterceptor {
    //被代理对象
    private Object target;
    public PayServiceCGLIBInterceptor(Object target) {
        this.target = target;
    }
    @Override
    public Object intercept(Object o, Method method, Object[] args, Method Proxy methodProxy) throws Throwable {
        //1.安全检查
        System.out.println("安全检查");
        //2.记录⽇志
        System.out.println("记录⽇志");
        //3.时间统计开始
        System.out.println("记录开始时间");
        //通过cglib的代理⽅法调⽤
        Object retVal = methodProxy.invoke(target, args);
        //4.时间统计结束
        System.out.println("记录结束时间");
        return retVal;
    }
    public static void main(String[] args) {
        PayService target = new AliPayService();
        PayService proxy = (PayService) Enhancer.create(target.getClass(), n
                ew PayServiceCGLIBInterceptor(target));
        proxy.pay();
    }
}
⑤ JDK 和 CGLIB 实现的区别
- JDK 实现,要求被代理类必须实现接⼝,之后是通过 InvocationHandler 及 Proxy,在运⾏时动态的在内存中⽣成了代理类对象,该代理对象是通过实现同样的接⼝实现(类似静态代理接⼝实现的⽅式),只是该代理类是在运⾏期时,动态的织⼊统⼀的业务逻辑字节码来完成。
- CGLIB 实现,被代理类可以不实现接⼝,是通过继承被代理类,在运⾏时动态的⽣成代理类对象。



















