AOP原理

什么是Aop

AOP(Aspect Orient Programming)也就是面向切面编程,作为面向对象编程的一种补充,已经成为一种比较成熟的编程方式。其实AOP问世的时间并不太长,AOP和OOP互为补充,面向切面编程将程序运行过程分解成各个切面

AOP的作用

作用:在不修改源代码的情况下,可以实现功能的增强。

AOP的基本概念

  • 切面(Aspect): 切面用于组织多个Advice,Advice放在切面中定义。
  • 连接点(Joinpoint): 程序执行过程中明确的点,如方法的调用,或者异常的抛出。在Spring AOP中,连接点总是方法的调用。
  • 增强处理(Advice): AOP框架在特定的切入点执行的增强处理。处理有"around"、"before"和"after"等类型
  • 切入点(Pointcut): 可以插入增强处理的连接点。简而言之,当某个连接点满足指定要求时,该连接点将被添加增强处理,该连接点也就变成了切入点。

AOP使用场景

  • 权限控制
  • 监控方法运行时间(监控性能)
  • 缓存优化(第一次调用查询数据库,将查询内存对象返回,不需要查询数据库)
  • 监控方法运行时间(监控性能)
  • 事务管理(调用方法前开启事务,调用方法后提交关闭事务)

AOP原理

如何动态修改功能

首先根据实际场合,抛出一个问题:

想在这些已经写好的方法上添加一个对应的日志处理工作,怎么办?

把每一个方法的前面和后面都加对应的日志处理即可3个方法可以自己手动改,如果有100个方法呢?当需要添加逻辑的方法比较多的时候,如果去修改每一个方法的源代码,肯定效率很低,因此能够有一种更好的方法按照某种匹配规则去匹配方法,然后添加对应的日志处理

如下图所示:
在这里插入图片描述

虽然上述提到用匹配的方式去添加对应的日志处理,我们只能做到手动去修改添加Java代码,那如何做到动态修改呢?

首先最终的Java代码在编译或运行期间会生成class文件,那么我们需要在生成class文件的过程,通过动态逻辑指定的位置生成相关处理即可

原理如下图所示:
在这里插入图片描述

AOP的编程思想

AOP是如何实现动态匹配,并且在何处位置可以插入相关的处理逻辑代码呢?需要我们去思考的地方

匹配方法流程如下图所示:
在这里插入图片描述

那些位置可以插入如下图所示:
在这里插入图片描述

那么可以结合AOP引入的几个重要的概念,与上述的思想结合如下图所示:
在这里插入图片描述

AOP面向切面编程操作

假设现在程序里面用到了5种通知,那么肯定需要执行这五种通知,每一种通知的执行先后顺序也是有要求,不可能先执行after再执行before。而AOP的设计引入了责任链模式来解决,类似于过滤器。
在这里插入图片描述

AOP通知执行的顺序

首先aop有五个通知类型,我们可以在使用这些通知的时候可以让它们按照顺序执行吗?

肯定是不可以的,举个最简单的例子,after能在before之前执行吗?肯定不能。

在这里插入图片描述

如果自己通过aop方式来实现某个统一的功能,我们该怎么做?

首先需要了解在什么时候处于事务的开始、事务的回滚、事务的提交

如下图所示:
在这里插入图片描述

结合通知,需要用到三个通知before、afterReturning、afterThrowing,还有一种方式在around里面嵌入afterThrowing也可行

而Spring提供一个TranscationInterceptor类,里面用到了三个通知before、afterReturning、afterThrowing。

代码执行流程

准备工作

准备工作

顺序内容
1定义一个切面类
2定义一个测试类
3定义主函数类
4定义spring配置文件

link

package com.hnyz.zmy.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * @ClassName: LogUtil
 * @Description:
 * @Author: Wei.Chen
 * @Date: 2021/7/19 16:56
 * @Version: 1.0.0
 */
@Aspect
@Component
public class LogUtil {
	/**
	 * 设置切点
	 */
	@Pointcut("execution(* com.hnyz.zmy.aop.Test.*(..))")
	private void myPointCut(){

	}

	@Around("myPointCut()")
	@Order(4)
	public Object around(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
		Signature signature = proceedingJoinPoint.getSignature();
		Object[] args = proceedingJoinPoint.getArgs();
		Object result = null;

		try {
			System.out.println("log---环绕通知start,"+signature.getName()+"方法开始执行,参数为:"+Arrays.toString(args));
			//通过反射的方式调用目标的方法,相当于执行method.invoke(),可以自己修改结果值
			result = proceedingJoinPoint.proceed(args);
			System.out.println("log---环绕通知stop,"+signature.getName()+"方法结束执行,参数为:"+Arrays.toString(args));
		}catch (Throwable throwable){
			System.out.println("log---环绕异常通知,"+signature.getName()+"出现异常");
			throw throwable;
		}finally {
			System.out.println("log---环绕返回通知,"+signature.getName()+"方法返回结果是:"+result);

		}
		return result;
	}

	@Before("myPointCut()")
	@Order(5)
	private int start(JoinPoint joinPoint){
		//获取方法签名
		Signature signature = joinPoint.getSignature();
		//获取参数信息
		Object[] args = joinPoint.getArgs();
		System.out.println("log---"+signature.getName()+"方法开始执行:参数是"+ Arrays.toString(args));
		return 100;
	}

	@After("myPoinitcut")
	@Order(3)
	public static void logFinally(JoinPoint joinPoint){
		Signature signature = joinPoint.getSignature();
		System.out.println("log---"+signature.getName()+"方法执行结束......over");
	}

	@AfterReturning(value = "myPoinitcut()", returning = "result")
	@Order(2)
	public static void stop(JoinPoint joinPoint, Object result){
		Signature signature = joinPoint.getSignature();
		System.out.println("log---"+signature.getName()+"方法执行结束,结果是:"+result);
	}


	@AfterThrowing(value = "myPoinitcut()", throwing = "e")
	@Order(1)
	public static void logException(JoinPoint joinPoint, Exception e){
		Signature signature = joinPoint.getSignature();
		System.out.println("log---"+signature.getName()+"方法抛出异常"+e.getMessage());
	}
}

定义一个测试类

package com.hnyz.zmy.aop;

/**
 * @ClassName: Test
 * @Description:
 * @Author: Wei.Chen
 * @Date: 2021/7/19 17:00
 * @Version: 1.0.0
 */
public class Test {

	public int add(int a, int b){

		return a + b;
	}


}

定义主程序类

package com.hnyz.zmy.aop;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @ClassName: AopTest
 * @Description:
 * @Author: Wei.Chen
 * @Date: 2021/7/19 17:22
 * @Version: 1.0.0
 */
public class AopTest {
	public static void main(String[] args) {
		//加载配置解析文件
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Aop.xml");
		Test test = (Test)applicationContext.getBean("test");
		int sum = test.add(20, 30);
		System.out.println("最终加法结果如下:"+sum);
	}
}

定义一个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: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/aop
	   http://www.springframework.org/schema/aop/spring-aop.xsd">

	<bean id="test" class="com.hnyz.zmy.aop.Test"></bean>
	<bean id="logUtil" class="com.hnyz.zmy.aop.LogUtil"></bean>
<!--	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>-->


	<aop:config>
		<aop:aspect ref="logUtil">
			<aop:pointcut id="poindcut" expression="execution(* com.hnyz.zmy.aop.Test.*(..))"/>
			<aop:around method="around" pointcut-ref="poindcut"/>
			<aop:before method="start" pointcut-ref="poindcut"/>
			<aop:after method="logFinally" pointcut-ref="poindcut"/>
			<aop:after-returning method="stop" returning="result" pointcut-ref="poindcut"/>
			<aop:after-throwing method="logException" throwing="e" pointcut-ref="poindcut"/>
		</aop:aspect>
	</aop:config>

</beans>

源码揭开面纱

启动主函数类
在这里插入图片描述

执行aop扫描的类时,首先会进入CglibAopProxy类的intercept方法,从advised中获取配置好的AOP通知,放入chain
在这里插入图片描述

执行内部调用的关键方法retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed()
在这里插入图片描述

进入proceed方法
在这里插入图片描述

proceed方法调用父类的proceed方法,即是RefleciveMethodInvocation类中的proceed方法

在这里插入图片描述

前面都可以称为准备工作,接下通过递归调用proceed方法完成通知工作,
通过索引获取对应的拦截器,索引为0获取的是ExposeInvocationInterceptor
在这里插入图片描述

经过一堆的拦截匹配判断后,调用ExposeInvocationInterceptor类的invoke方法,
在这里插入图片描述

进入ExposeInvocationInterceptor中进行参数设置
在这里插入图片描述
然后回调proceed方法,再次进入RefleciveMethodInvocation类中的proceed方法,获取下一个对应的拦截器AspectJAfterThrowingAdvice
在这里插入图片描述

同上最终通过AspectJAfterThrowingAdvice调用invoke方法
在这里插入图片描述

回调proceed方法回到RefleciveMethodInvocation类中的proceed方法,通过下标获取拦截器AfterReturnAdviceIntercetor
在这里插入图片描述

同上执行invoke方法进入AfterReturnAdviceIntercetor类中invoke方法
在这里插入图片描述

可以看到调用proceed方法下面还有一行this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());,这个是在程序返回时才执行,所以暂时会回到RefleciveMethodInvocation类中的proceed方法,获取下一个对应的拦截器AspectJAfterAdvice
在这里插入图片描述

这里的步骤省略,还是回调,获取下一个对应的拦截器AspectJAfterAdvice,调用invoke方法,然后调用invokeAdviceMethod方法
在这里插入图片描述

调用invokeAdviceMethodWithGivenArgs执行return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);
在这里插入图片描述

进入LogUtil的around方法
在这里插入图片描述

然后执行proceed方法,再次获取下一个拦截器interceptorOrInterceptionAdive
在这里插入图片描述

其原理跟around差不多,只是around多了一个returning,到现在为止只有before执行完毕,around执行了一半,afterafterReturningafterThrowing都没有执行相关的逻辑代码。after等返回结果之后再执行,而afterReturning是在计算结果时执行,afterThrowing出现异常时执行

最终可以发现主要是围绕chain对象进行回调执行通知

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring AOP(Aspect-Oriented Programming)是一种基于面向切面编程的技术,它通过将一个应用程序分解成许多独立的部分,从而提高了应用程序的模块化程度,同时也提高了代码的可重用性和可维护性。 Spring AOP 是在运行时对程序进行修改的,它不需要重新编译源代码,因此使得代码的维护和修改更加方便。Spring AOP 原理主要分为以下几个方面: 1. 切面(Aspect):切面是一个类,其中包含了一组相关的Advice和其他相关的代码,用于在目标对象的方法执行前、执行后或者抛出异常时执行相应的操作。 2. 连接点(Join point):连接点是指在应用程序的执行过程中,可以被切面拦截的点,比如方法调用、异常抛出、属性赋值等。 3. 通知(Advice):通知是指在连接点处执行的代码,有多种类型的通知,包括前置通知(Before advice)、后置通知(After advice)、返回通知(After returning advice)、异常通知(After throwing advice)和环绕通知(Around advice)。 4. 切入点(Pointcut):切入点是一个表达式,用于定义哪些连接点会被切面拦截。 5. 代理(Proxy):代理是指在目标对象和切面之间创建的对象,它可以拦截目标对象的方法调用,并在方法执行前后执行相应的通知。 Spring AOP 的实现机制主要是通过 JDK 动态代理或者 CGLIB 动态代理来实现的。当目标对象实现了接口时,Spring AOP 使用 JDK 动态代理,否则使用 CGLIB 动态代理。在 JDK 动态代理中,代理对象实现了与目标对象相同的接口,而在 CGLIB 动态代理中,代理对象是目标对象的子类。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值