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

相关文章

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

python panda库从基础到高级操作分析

《pythonpanda库从基础到高级操作分析》本文介绍了Pandas库的核心功能,包括处理结构化数据的Series和DataFrame数据结构,数据读取、清洗、分组聚合、合并、时间序列分析及大数据... 目录1. Pandas 概述2. 基本操作:数据读取与查看3. 索引操作:精准定位数据4. Group

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

MySQL中EXISTS与IN用法使用与对比分析

《MySQL中EXISTS与IN用法使用与对比分析》在MySQL中,EXISTS和IN都用于子查询中根据另一个查询的结果来过滤主查询的记录,本文将基于工作原理、效率和应用场景进行全面对比... 目录一、基本用法详解1. IN 运算符2. EXISTS 运算符二、EXISTS 与 IN 的选择策略三、性能对比

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.