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

相关文章

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2