什么是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配置文件 |
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
* @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
* @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
* @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>
源码揭开面纱
启动主函数类
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
执行了一半,after
、afterReturning
、afterThrowing
都没有执行相关的逻辑代码。after
等返回结果之后再执行,而afterReturning
是在计算结果时执行,afterThrowing
出现异常时执行
最终可以发现主要是围绕chain对象进行回调执行通知
原文始发于微信公众号(行走318川藏线):AOP执行原理
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/20872.html