Spring-AOP

1. 概述

Spring的AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架的一个重要特性,它提供了一种以声明的方式来实现横切关注点的功能。AOP通过将横切关注点(如事务管理、日志记录、安全性等)从核心业务逻辑中分离出来,使得代码更加模块化、可维护和可复用。

2. 相关术语

在Spring中,AOP的实现主要依赖于以下几个核心概念:

  1. 切面(Aspect):切面是一个跨越多个对象的模块化单元,用于封装横切关注点的行为。切面由切点和通知组成,切点定义了在哪些连接点上应用通知,通知定义了在连接点上执行的具体操作。封装通知方法的类
  2. 连接点(Join Point):连接点是程序执行过程中能够插入切面的点,如方法的调用或异常的抛出等。通俗说,就是spring允许你使用通知的地方
  3. 切点(Pointcut):切点是连接点的集合,它定义了在哪些连接点上应用通知。切点可以使用表达式或注解来定义。
  4. 通知(Advice):通知定义了在切点上执行的具体操作,如在方法调用前执行、在方法返回后执行等。Spring提供了几种常见的通知类型,包括前置通知、后置通知、异常通知、环绕通知等。
  5. 织入(Weaving):织入是将切面应用到目标对象中,并创建一个新的代理对象的过程。织入可以在编译时、类加载时或运行时进行。

Spring提供了多种方式来实现AOP,包括基于XML配置、基于注解的配置和基于Java配置。开发人员可以根据需求选择适合的方式来配置和管理切面。通过AOP,开发人员可以将横切关注点与核心业务逻辑分离,并提供一种灵活的方式来添加和管理应用程序中的横切功能。

3. 基于注解的AOP

动态代理是一种在运行时生成代理对象的技术,它可以在不修改原始对象的情况下,对原始对象进行功能增强或拦截。在Java中,有两种主要的动态代理方式:基于接口的代理和基于类的代理。

无论是基于接口的代理还是基于类的代理,它们都提供了一种机制来在运行时生成代理对象,并允许对方法调用进行拦截和增强。动态代理可以用于实现各种功能,如性能监控、事务管理、日志记录等。在Spring框架中,动态代理被广泛用于实现AOP功能,通过代理对象来添加横切关注点的行为。
在这里插入图片描述

  • 动态代理分为JDK动态代理和cglib动态代理
  • 当目标类有接口的情况使用JDK动态代理和cglib动态代理,没有接口时只能使用cglib动态代理
  • JDK动态代理动态生成的代理类会在com.sun.proxy包下,类名为$proxy1,和目标类实现相同的接口
  • cglib动态代理动态生成的代理类会和目标在在相同的包下,会继承目标类
  • 动态代理(InvocationHandler):JDK原生的实现方式,需要被代理的目标类必须实现接口。因为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。
  • cglib:通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。
  • AspectJ:是AOP思想的一种实现。本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。

4. 示例(基于Spring6+JDK17)

AOP通过将横切关注点(日志记录)从核心业务逻辑中分离出来,使得代码更加模块化、可维护和可复用。

4.1. 添加依赖

<dependencies>
    <!--spring context依赖-->
    <!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.0.2</version>
    </dependency>

    <!--spring aop依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>6.0.2</version>
    </dependency>
    <!--spring aspects依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>6.0.2</version>
    </dependency>

    <!--junit5测试-->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.3.1</version>
    </dependency>

    <!--log4j2的依赖-->
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.19.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j2-impl</artifactId>
        <version>2.19.0</version>
    </dependency>
</dependencies>

4.2. 目标接口与实现类

接口:

public interface Calculator {
    
    int add(int i, int j);
    
}

实现类:

@Component
public class CalculatorImpl implements Calculator {
    
    @Override
    public int add(int i, int j) {
        int result = i + j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
}

4.3. 创建切面类并配置

切面类:

// @Aspect表示这个类是一个切面类
@Aspect
// @Component注解保证这个切面类能够放入IOC容器
@Component
public class LogAspect {

    /**
     * 重用切入点表达式
     */
    @Pointcut("execution(* com.gan.proxy.CalculatorImpl.*(..))")
    public void pointCut(){}

    /**
     * beforeMethod():切面(封装通知方法的类)
     * @Before:通知类型
     * @Before(value="切入点表达式")
     * 各种通知的执行顺序:
     * - Spring版本5.3.x以前:
     *   - 前置通知
     *   - 目标操作
     *   - 后置通知
     *   - 返回通知或异常通知
     * - Spring版本5.3.x以后:
     *   - 前置通知
     *   - 目标操作
     *   - **返回通知或异常通知**
     *   - **后置通知**
     *
     */
    @Before("execution(public int com.gan.proxy.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
    }

    @After("execution(* *..*.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->后置通知,方法名*:"+methodName);
    }

    @AfterReturning(value = "pointCut()", returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, Object result){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->返回通知,方法名:"+methodName+",结果:"+result);
    }

    @AfterThrowing(value = "pointCut()", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->异常通知,方法名:"+methodName+",异常:"+ex);
    }

    @Around(value = "pointCut()")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        Object result = null;
        try {
            System.out.println("环绕通知-->目标对象方法执行之前");

            //目标对象(连接点)方法的执行(通俗说,就是spring允许你使用通知的地方)
            result = joinPoint.proceed();

            System.out.println("环绕通知-->目标对象方法返回值之后");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.out.println("环绕通知-->目标对象方法出现异常时");
        } finally {
            System.out.println("环绕通知-->目标对象方法执行完毕");
        }
        return result;
    }
}

spring-aop.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--
        基于注解的AOP的实现:
        1、将目标对象和切面交给IOC容器管理(注解+扫描)
        2、开启AspectJ的自动代理,为目标对象自动生成代理
        3、将切面类通过注解@Aspect标识
    -->
    <context:component-scan base-package="com.*"></context:component-scan>

    <!--开启AspectJ的自动代理,为目标对象自动生成代理-->
    <aop:aspectj-autoproxy/>
</beans>

4.4. 测试

public class AopTest {

    @Test
    public void testAdd(){
        ApplicationContext ac = 
        new ClassPathXmlApplicationContext("spring-aop.xml");
        Calculator calculator = ac.getBean(Calculator.class);
        int add = calculator.add(1, 1);
        System.out.println("执行成功:" + add);
    }
}

4.5. 结果

在这里插入图片描述

5. 通知类型

  • 前置通知:使用@Before注解标识,在被代理的目标方法执行
  • 返回通知:使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行(寿终正寝
  • 异常通知:使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行(死于非命
  • 后置通知:使用@After注解标识,在被代理的目标方法最终结束后执行(盖棺定论
  • 环绕通知:使用@Around注解标识,使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置

各种通知的执行顺序:

  • Spring版本5.3.x以前:
    • 前置通知
    • 目标操作
    • 后置通知
    • 返回通知或异常通知
  • Spring版本5.3.x以后:
    • 前置通知
    • 目标操作
    • 返回通知或异常通知
    • 后置通知

6. 切入点

6.1. 表达式语法

在这里插入图片描述
示例:

@After("execution(* *..*.*(..))")
public void afterMethod(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->后置通知,方法名*:"+methodName);
}

6.2. 复用切入点表达式

  1. 声明
@Pointcut("execution(* com.xxx.*.*(..))")
public void pointCut(){}
  1. 在同一个切面(类)中使用
@Before("pointCut()")
public void beforeMethod(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}
  1. 在不同切面(类)中使用
@Before("声明类路径.pointCut()")
public void beforeMethod(JoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}

7. 获取通知的相关信息

7. 获取连接点信息

获取连接点信息可以在通知方法的参数位置设置JoinPoint类型的形参(环绕通知使用:ProceedingJoinPoint)

@Before("execution(* com.xxx.*.*(..))")
public void beforeMethod(JoinPoint joinPoint){
    //获取连接点的签名信息
    String methodName = joinPoint.getSignature().getName();
    //获取目标方法到的实参信息
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}

7. 获取目标方法的返回值

@AfterReturning中的属性returning,用来将通知方法的某个形参,接收目标方法的返回值

@AfterReturning(value = "pointCut()", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->返回通知,方法名:"+methodName+",结果:"+result);
}

7. 获取目标方法的异常

@AfterThrowing中的属性throwing,用来将通知方法的某个形参,接收目标方法的异常

 @AfterThrowing(value = "pointCut()", throwing = "ex")
 public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
     String methodName = joinPoint.getSignature().getName();
     System.out.println("Logger-->异常通知,方法名:"+methodName+",异常:"+ex);
 }

8. 切面

封装通知方法的类。
![在这里插入图片描述](https://img-blog.csdnimg.cn/d7a67e726e534f72a0705bb91bea758c.png
切面的优先级:
相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。

  • 优先级高的切面:外面
  • 优先级低的切面:里面

使用@Order注解可以控制切面的优先级:

  • @Order(较小的数):优先级高
  • @Order(较大的数):优先级低
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值