Spring 源码分析衍生篇十二 :AOP 中的引介增强

2023-11-29 20:10

本文主要是介绍Spring 源码分析衍生篇十二 :AOP 中的引介增强,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一、前言
  • 二、功能介绍
    • 1. 关键类
      • 1.1 DynamicIntroductionAdvice
      • 1.2 IntroductionAdvisor
    • 2. 演示 Demo
  • 三、原理分析
    • 1. ProxyFactory#addAdvisor
    • 2. aopPlusDemo.sayPlus("IAopPlusDemo")

一、前言

本文是 Spring源码分析:Spring源码分析二十四 : cglib 的代理过程 的衍生文章。主要是因为本人菜鸡,在分析源码的过程中还有一些其他的内容不理解,故开设衍生篇来完善内容以学习。

全集目录:Spring源码分析:全集整理


本文需要辅以前文观看,建议阅读:

本文系列:

  1. Spring源码分析十一:@Aspect方式的AOP上篇 - @EnableAspectJAutoProxy
  2. Spring源码分析十二:@Aspect方式的AOP中篇 - getAdvicesAndAdvisorsForBean
  3. Spring源码分析十三:@Aspect方式的AOP下篇 - createProxy
  4. Spring源码分析二十四:cglib 的代理过程

本文衍生篇:

  1. Spring 源码分析衍生篇九 : AOP源码分析 - 基础篇
  2. Spring 源码分析衍生篇十二 :AOP 中的引介增强

补充篇:

  1. Spring 源码分析补充篇三 :Spring Aop 的关键类

二、功能介绍

引介增强是一种比较特殊的增强类型,它不是在目标方法周围织入增强,而是为目标创建新的方法和属性,所以它的连接点是类级别的而非方法级别的。

通过引介增强我们可以为目标类添加一个接口的实现即原来目标类未实现某个接口,那么通过引介增强可以为目标类创建实现某接口的代理。

1. 关键类

Spring Aop 为了 引介增强功能提供了 最基础的 DynamicIntroductionAdvice 和 IntroductionAdvisor接口。

1.1 DynamicIntroductionAdvice

DynamicIntroductionAdvice 有一个子接口和两个实现类,结构如下(部分其他接口并未画出):
在这里插入图片描述
我们一般不会直接使用 DynamicIntroductionAdvice ,而是使用Spring帮我们封装好的 DelegatingIntroductionInterceptor。

1.2 IntroductionAdvisor

IntroductionAdvisor 有两个实现类, 结构如下(部分其他接口并未画出):在这里插入图片描述
同样,我们一般也不会使用IntroductionAdvisor 接口,而是使用 DefaultIntroductionAdvisor。

2. 演示 Demo

下面直接演示一个 Demo

// 代理接口
public interface IAopDemo {void say(String msg);
}
// 引介增强的接口
public interface IAopPlusDemo {void sayPlus(String msg);
}
// 代理接口的实现类
public class AopDemo implements IAopDemo {public void say(String msg) {System.out.println("AopDemo.say : " + msg);}
}// 引介拦截器的实现。这里注意,如果使用DelegatingIntroductionInterceptor,则需要强制实现增强的接口,比如这里是 IAopPlusDemo 接口
public class CustomIntroductionInterceptor extends DelegatingIntroductionInterceptor implements IAopPlusDemo {@Overridepublic void sayPlus(String msg) {System.out.println("CustomIntroductionInterceptor.sayPlus : " + msg);}
}// main 方法
public class IntroductionMain {public static void main(String[] args) {ProxyFactory factory = new ProxyFactory(new AopDemo());factory.setProxyTargetClass(true);// 创建顾问,指定 Advice 和 引介增强接口 IAopPlusDemoAdvisor advisor = new DefaultIntroductionAdvisor(new CustomIntroductionInterceptor(), IAopPlusDemo.class);factory.addAdvisor(advisor);final Object proxy = factory.getProxy();// 执行 IAopDemo 的 say 方法IAopDemo aopDemo = (IAopDemo) proxy;aopDemo.say("IAopDemo");// 执行 引介增强 接口 IAopPlusDemo  的 sayPlus  方法IAopPlusDemo aopPlusDemo = (IAopPlusDemo) proxy;aopPlusDemo.sayPlus("IAopPlusDemo");}
}

上面的例子中我们可以看到,我们代理的是 类是 AopDemo 实现了 IAopDemo 接口,并没有实现IAopPlusDemo 。而我们通过引介增强,代理对象不仅可以调用IAopDemo 的方法,也可以调用 IAopPlusDemo。

三、原理分析

我们以上面的 Demo 作为开端,如下:

    public static void main(String[] args) {ProxyFactory factory = new ProxyFactory(new AopDemo());factory.setProxyTargetClass(true);Advisor advisor = new DefaultIntroductionAdvisor(new CustomIntroductionInterceptor(), IAopPlusDemo.class);// 1. 添加 DefaultIntroductionAdvisor 顾问到 ProxyFactory 中factory.addAdvisor(advisor);final Object proxy = factory.getProxy();IAopDemo aopDemo = (IAopDemo) proxy;aopDemo.say("IAopDemo");IAopPlusDemo aopPlusDemo = (IAopPlusDemo) proxy;// 2. 调用 引介增强接口 IAopPlusDemo  的方法。这里实际会调用 CustomIntroductionInterceptor#sayPlus 方法 aopPlusDemo.sayPlus("IAopPlusDemo");}

1. ProxyFactory#addAdvisor

首先我们知道 ProxyFactory 在创建代理对象时会添加顾问,用来进行增强。而我们这里添加的顾问为 DefaultIntroductionAdvisor。

ProxyFactory#addAdvisor 调用的是 AdvisedSupport#addAdvisor(org.springframework.aop.Advisor) 方法,实现如下:

	@Overridepublic void addAdvisor(Advisor advisor) {int pos = this.advisors.size();// 添加当前顾问到集合中addAdvisor(pos, advisor);}@Overridepublic void addAdvisor(int pos, Advisor advisor) throws AopConfigException {// 如果顾问类型是 IntroductionAdvisor,需要进行校验if (advisor instanceof IntroductionAdvisor) {// 对顾问进行校验validateIntroductionAdvisor((IntroductionAdvisor) advisor);}// 添加顾问到 集合中。addAdvisorInternal(pos, advisor);}private void validateIntroductionAdvisor(IntroductionAdvisor advisor) {// 校验引介增强 Advice 的接口合法性advisor.validateInterfaces();// If the advisor passed validation, we can make the change.// 获取引介增强的接口Class<?>[] ifcs = advisor.getInterfaces();for (Class<?> ifc : ifcs) {// 添加到 ProxyFactory的接口集合中addInterface(ifc);}}

其中 advisor.validateInterfaces(); 在我们这的实现是 DefaultIntroductionAdvisor#validateInterfaces,如下:

	@Overridepublic void validateInterfaces() throws IllegalArgumentException {// 这里的接口可以在 DefaultIntroductionAdvisor 构造时指定也可以通过 addInterface 方法添加。for (Class<?> ifc : this.interfaces) {// 这里要求 advice 必须是 DynamicIntroductionAdvice 实现类 && advice  必须实现了指定的引介增强接口if (this.advice instanceof DynamicIntroductionAdvice &&!((DynamicIntroductionAdvice) this.advice).implementsInterface(ifc)) {throw new IllegalArgumentException("DynamicIntroductionAdvice [" + this.advice + "] " +"does not implement interface [" + ifc.getName() + "] specified for introduction");}}}

这里我们可以知道:当我们使用 DefaultIntroductionAdvisor 作为顾问时,在 将其添加到 ProxyFactory 中时会调用 DefaultIntroductionAdvisor#validateInterfaces 来校验 内部的 DynamicIntroductionAdvice 是否实现了 引介增强接口。

所以我们在Demo中的 CustomIntroductionInterceptor 需要实现 IAopPlusDemo 接口。

2. aopPlusDemo.sayPlus(“IAopPlusDemo”)

aopPlusDemo.sayPlus("IAopPlusDemo") 方法在调用时实际调用的是 CustomIntroductionInterceptor#sayPlus 方法。下面我们需要知道在调用方法时发生了什么会出现这种情况。

在Spring源码分析二十四:cglib 的代理过程 中我们描述了 Cglib 代理对象调用方法的过程 :

  1. 当我们调用aopPlusDemo.sayPlus("IAopPlusDemo") 方法时,代理对象会将此次调用交由 DynamicAdvisedInterceptor来处理。

  2. DynamicAdvisedInterceptor 会获取适用于当前方法的拦截器和建议。 获取过程逻辑大致如下: 遍历 ProxyFactory 中的所有 Advisor,判断是否匹配当前类和方法。如果匹配,获取其内部的拦截器,并返回。以上面的 Demo为例,我们使用的是 DefaultIntroductionAdvisor,DefaultIntroductionAdvisor 实现了 IntroductionAdvisor接口,因此在判断时仅会精确到类级别。

    1. ia.getClassFilter().matches(actualClass) 调用的是DefaultIntroductionAdvisor#matches(Class<?> clazz) ,其结果恒为 true,表明 DefaultIntroductionAdvisor 适用于所有类。
      在这里插入图片描述
    2. registry.getInterceptors(advisor) 这里返回的是 DefaultIntroductionAdvisor的 advice ,即我们Demo中的 CustomIntroductionInterceptor 实例。
    3. 因此 DynamicAdvisedInterceptor 会获取到可以用于当前增强的拦截器CustomIntroductionInterceptor 。
  3. CustomIntroductionInterceptor 获取到拦截器后会通过 CglibMethodInvocation#proceed 来执行方法。CglibMethodInvocation#proceed 调用其父类 ReflectiveMethodInvocation#proceed 来执行方法。

  4. ReflectiveMethodInvocation#proceed 执行 MethodInterceptor#invoke 方法。而我们上面提到我们这里的拦截器实际上是 CustomIntroductionInterceptor 。因此调用的方法是 CustomIntroductionInterceptor#invoke ,其实现如下 :

    	public Object invoke(MethodInvocation mi) throws Throwable {// 如果当前接口是,引介增强的接口,如这里为 IAopPlusDemoif (isMethodOnIntroducedInterface(mi)) {// 直接执行delegate 的方法Object retVal = AopUtils.invokeJoinpointUsingReflection(this.delegate, mi.getMethod(), mi.getArguments());if (retVal == this.delegate && mi instanceof ProxyMethodInvocation) {Object proxy = ((ProxyMethodInvocation) mi).getProxy();if (mi.getMethod().getReturnType().isInstance(proxy)) {retVal = proxy;}}return retVal;}// 如果不是,传递给cglib 的 下一个拦截器调用return doProceed(mi);}
    
  5. 我们可以看到 CustomIntroductionInterceptor#invoke 如果发现调用方法是引介增强的方法,则会直接交由 CustomIntroductionInterceptor#delegate 执行。而 CustomIntroductionInterceptor#delegate 默认值就是 CustomIntroductionInterceptor 实例自身,所以在调用引介增强接口方法时会调用到 CustomIntroductionInterceptor 。


以上:内容部分参考
https://blog.csdn.net/f641385712/article/details/89303088
https://blog.csdn.net/yangshangwei/article/details/77187198
如有侵扰,联系删除。 内容仅用于自我记录学习使用。如有错误,欢迎指正

这篇关于Spring 源码分析衍生篇十二 :AOP 中的引介增强的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/434147

相关文章

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

关于MyISAM和InnoDB对比分析

《关于MyISAM和InnoDB对比分析》:本文主要介绍关于MyISAM和InnoDB对比分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录开篇:从交通规则看存储引擎选择理解存储引擎的基本概念技术原理对比1. 事务支持:ACID的守护者2. 锁机制:并发控制的艺

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja