Spring中引入增强(IntroductionAdvice)的底层实现原理

简介: 一个 Java 类,没有实现A接口,在不修改Java类的情况下,使其具备A接口的功能。

Spring中有五种增强:BeforeAdvide(前置增强)、AfterAdvice(后置增强)、ThrowsAdvice(异常增强)、RoundAdvice(环绕增强)、IntroductionAdvice(引入增强)

RoundAdvice(环绕增强):就是 BeforeAdvide(前置增强)、AfterAdvice(后置增强)的组合使用叫环绕增强。

前四种增强都比较简单,我们今天要介绍的是 IntroductionAdvice(引入增强)的概念及原理。

引入增强(Introduction Advice)的概念:一个 Java 类,没有实现A接口,在不修改Java类的情况下,使其具备A接口的功能。

1.Cglib 实现引入增强

记住,我的目的不是告诉你怎么在 Spring 中使用引入增强功能(这不是我的风格),而是探究引入增强功能的底层实现原理。

public interface IHello {
   

    public void sayHello();
}

上面是接口功能,CeremonyService 是需要增强的类,在不改变 CeremonyService 类的情况下,使其具备 IHello 接口功能。

public class CeremenyService {
   

    public void sayBye() {
   
        System.out.println("Say bye from Ceremeny.");
    }

}

看起来要像下面这样:

CeremenyService cs;

IHello ih = (IHello) cs;
ih.sayHello();

即,CeremenyService 居然变成了 IHello 类型。

我们编写一个重要的拦截器,来实现此功能。

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import x.y.IHello;

public class IntroInterceptor implements MethodInterceptor, IHello {
   
        // 实现了IHello增强接口的对象
    private Object delegate;

    public IntroInterceptor() {
   
        this.delegate = this;
    }

    public IntroInterceptor(Object delegate) {
   
        this.delegate = delegate;
    }

    @Override
    public void sayHello() {
   
        System.out.println("Say hello from delegate.");
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
   
        Class<?> clz = method.getDeclaringClass();
        if (clz.isAssignableFrom(IHello.class)) {
   
                // 如果实现了IHello增强接口,则调用实现类delegate的方法
            return method.invoke(delegate, args);
        }
        return methodProxy.invokeSuper(obj, args);
    }
}

我们来编写一个测试类。

public static void main(String[] args) {
   
    Enhancer en = new Enhancer();
    en.setSuperclass(CeremenyService.class);
    en.setInterfaces(new Class[] {
    IHello.class });
    en.setCallback(new IntroInterceptor());

    CeremenyService cs = (CeremenyService) en.create();
    cs.sayBye();

    IHello ih = (IHello) cs;
    ih.sayHello();
}

en.setInterfaces(new Class[] { IHello.class }); 非常重要,表示 Cglib 生成代理类,将要实现的接口集合。

于是生成的代理类 Class,类似于:

public class CeremenyServiceEnhancerByCGLIB*E*n*h*a*n*c*e*r*B*y**C\G\L\I\B\86859be5 extends CeremenyService implements IHello**

输出结果:

Say bye from Ceremeny.
Say hello from delegate.

这就是大名鼎鼎的引入增强(Introduction Advice)的底层实现原理。

2. Spring framework 引入增强源码解读

Spring 的 xml 文件配置。

<bean id="ceremonyService" class="x.y.service.CeremonyService" />
<bean id="ceremonyIntroAdvice" class="x.y.advice.CeremonyIntroAdvice" />

<bean id="ceremonyProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="interfaces" value="x.y.IHello"/>                   <!-- 需要动态实现的接口 -->
        <property name="target" ref="ceremonyService"/>                    <!-- 目标类 -->
        <property name="interceptorNames" value="ceremonyIntroAdvice"/>    <!-- 引入增强 -->
        <property name="proxyTargetClass" value="true"/>                   <!-- 代理目标类(默认为 false,代理接口) -->
</bean>

我们需要自定义一个拦截器。

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;

import x.y.IHello;

@SuppressWarnings("serial")
public class CeremonyIntroAdvice extends DelegatingIntroductionInterceptor implements IHello {
   

    @Override
    public Object invoke(MethodInvocation mi) throws Throwable {
   
        return super.invoke(mi);
    }

    @Override
    public void sayHello() {
   
        System.out.println("Say hello.");
    }

}

在 Spring 中,要实现引入增强,需要继承自 DelegatingIntroductionInterceptor。

下面看看该 DelegatingIntroductionInterceptor 类的 invoke() 方法源码。

@Override
    public Object invoke(MethodInvocation mi) throws Throwable {
   
            // 检测是否是引入增强
        if (isMethodOnIntroducedInterface(mi)) {
   
            // 执行实现了引入增强接口的delegate对象的增强方法
            Object retVal = AopUtils.invokeJoinpointUsingReflection(this.delegate, mi.getMethod(), mi.getArguments());

            // Massage return value if possible: if the delegate returned itself,
            // we really want to return the proxy.
            if (retVal == this.delegate && mi instanceof ProxyMethodInvocation) {
   
                Object proxy = ((ProxyMethodInvocation) mi).getProxy();
                if (mi.getMethod().getReturnType().isInstance(proxy)) {
   
                    retVal = proxy;
                }
            }
            return retVal;
        }

        return doProceed(mi);
    }

AopUtils.invokeJoinpointUsingReflection() 方法内部,其实就是反射方法调用。

try {
   
    ReflectionUtils.makeAccessible(method);
    return method.invoke(target, args);
}

最后写一个测试方法,来测试一下。

public static void main(String[] args) {
   

    FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
            "D:/workspace/Spring4.2.5/bin/applicationContext.xml");

    CeremonyService service = context.getBean("ceremonyProxy", CeremonyService.class);
    service.sayBye();

    IHello hello = (IHello) service;
    hello.sayHello();

    context.close();
}

输出:

Say bye.
Say hello.

总结:介绍如何使用的文章比较多,而介绍原理性的文章少一些,我比较喜欢介绍原理性的文章。希望本篇博文,对您有用。

作者:祖大俊
来源:https://my.oschina.net/zudajun/blog/663962

相关文章
|
4月前
|
前端开发 Java 数据库连接
Spring Boot 详细简介!
Spring Boot 是什么?能干啥?
372 0
Spring Boot 详细简介!
|
4月前
|
JSON fastjson Java
阿里巴巴为什么不建议 boolean 类型变量用 isXXX
为什么不推荐使用 isXXX 来命名呢?到底是用基本类型的数据好呢还是用包装类好呢?
218 3
阿里巴巴为什么不建议 boolean 类型变量用 isXXX
|
4月前
|
缓存 编译器 Android开发
[Android 从零到一] Compose LazyColumn 性能优化:key、稳定性与重组治理
本文深入剖析 LazyColumn 性能问题三大根源:key 配置错误、数据类型不稳定、重组作用域过大,结合实例详解 key 选型、@Immutable 应用、derivedStateOf 隔离、状态下沉等可落地优化方案,助你彻底解决列表闪烁、卡顿与无效重组。
275 7
|
4月前
|
Oracle Java 关系型数据库
Linux 安装 JDK 环境
由于 JDK1.8.202 是最后一个免费版本,建议下载此版本。由于在 Oracle 官方网站下载需要登录,可通过华为云镜像下载。
821 1
Linux 安装 JDK 环境
|
4月前
|
Java API Maven
Spring Boot 创建项目详细介绍
如何创建一个 Spring Boot 项目,以及自动生成的目录文件作用。
328 2
|
4月前
|
XML 人工智能 前端开发
把 GLM-5.3 接入到 DeepSeek Harness,夯爆了!
GLM-5.3 + Kimi K3 + DeepSeek V4 Pro 模型同时接入 DeepSeek Harness,前端 + 后端全栈 2 大任务横评测试,到底谁是 AI 编程之王?
894 0
|
4月前
|
监控 Java 数据库连接
SpringBoot3全栈开发实战:从入门到精通的完整指南
本文是SpringBoot3的精要总结,涵盖自动配置、起步依赖、嵌入式服务器等核心特性,详解项目搭建、YAML配置、Web开发、MyBatis整合、热部署、定时任务、Actuator监控及原生镜像等高级功能,并附思维导图助快速复习。
394 0
SpringBoot3全栈开发实战:从入门到精通的完整指南
|
4月前
|
人工智能 安全 测试技术
【AI时代软件项目管理系列】4. AI 时代的软件项目启动:从立项评估到 AI 可行性分析
AI 并没有让瀑布型项目失效,尤其在政企、定制化和交付型项目中,合同范围、预算、里程碑、阶段评审和最终验收仍然需要明确治理。真正需要改变的是传统严格串行的管理方式。AI 时代的瀑布项目应保留阶段、基线和责任机制,同时引入快速反馈、持续验证和 AI/Agent 赋能,让需求、设计、开发、测试和交付形成更高效的闭环,实现“治理不失控、执行更敏捷”。
253 1
|
4月前
|
缓存 Java 虚拟化
[鸿蒙从零到一] HarmonyOS 性能优化:启动、渲染与内存的系统治理
本文系统解析HarmonyOS应用性能优化三大核心:冷启动加速(延迟初始化、骨架屏)、ArkUI渲染提效(细粒度状态、LazyForEach、扁平布局)、内存健康治理(泄漏排查、LRU缓存、主动释放),附ArkTS实战代码与DevEco工具指南
338 1
|
4月前
|
人工智能 测试技术 Shell
OpenCode开源AI编程助手实操:替代Claude Code对接百炼完整教程
在AI编程Agent快速普及的当下,很多开发者习惯使用闭源编程代理工具完成项目重构、bug修复、新功能开发,但闭源工具存在诸多现实痛点。一方面工具完全绑定自家模型,无法自由切换推理后端;另一方面账号风控策略严苛,容易出现账号受限、调用中断的情况,企业内部开发还会面临代码数据外送带来的数据安全风险。OpenCode作为一款开源AI编程代理框架,被很多开发者视作Claude Code的优质替代方案,它不绑定任何大模型厂商,支持对接云端大模型服务,也可以接入本地私有化部署模型,同时完整复刻终端Agent的文件读写、命令执行、项目分析等核心能力,搭配百炼平台的各类代码大模型,就可以搭建一套完全自主可控
612 1

热门文章

最新文章