Spring之CGLIB和JDK动态代理底层实现

embedded/2024/10/18 0:25:15/

目录

CGLIB

使用示例-支持创建代理对象,执行代理逻辑

使用示例-多个方法,走不同的代理逻辑

JDK动态代理

使用示例-支持创建代理对象,执行代理逻辑

ProxyFactory

如何自动在CGLIB和JDK动态代理转换

使用示例-使用CGLIB代理方式

使用示例-使用JDK动态代理方式


Spring会自动在JDK动态代理和CGLIB之间转换:

1、如果目标对象实现了接口,默认情况下会采用JDK的动态代理实现AOP

2、如果目标对象实现了接口,可以强制使用CGLIB实现AOP

3、如果目标对象没有实现了接口,必须采用CGLIB库

本文主要讲解CGLIB和JDK动态代理的使用和底层原理,以及Spring如何自动在JDK动态代理和CGLIB之间转换

CGLIB

CGLIB动态代理是利用ASM开源包,对代理对象类的class文件加载进来,通过修改其字节码生成子类来处理。

使用示例-支持创建代理对象,执行代理逻辑

新建一个UserService类,这个类是目标类,后续会被代理

java">public class UserService {public void test() {System.out.println("userService execute test....");}
}

使用Enhancer类设置代理类UserService,设置代理逻辑,创建代理对象

java">public class CylTest {public static void main(String[] args) {UserService target = new UserService();Enhancer enhancer = new Enhancer();enhancer.setSuperclass(UserService.class);//设置代理逻辑enhancer.setCallbacks(new Callback[]{new MethodInterceptor() {@Overridepublic Object intercept(/*目标对象*/Object o,/*目标对象方法*/Method method,/*参数*/Object[] args,/*代理对象方法*/MethodProxy methodProxy) throws Throwable {System.out.println("before");Object result = method.invoke(target, args);System.out.println("after");return result;}}});//创建代理对象=>类型是UserService,但却是代理对象UserService userService = (UserService) enhancer.create();userService.test();}
}

这个阶段会产生三个对象:

1.目标对象-targetUserService

2.负责创建代理对象的工厂对象enhancer

3.代理对象-proxyUserService

最终执行效果:

before

userService execute test....

after

使用示例-多个方法,走不同的代理逻辑

新建一个UserService类,设置两个方法

java">public void test() {System.out.println("userService execute test....");}public void a() {System.out.println("userService execute a....");}

在enhancer对象中设置两个代理逻辑,test方法走代理逻辑1,a方法走代理逻辑2

java">public static void main(String[] args) {UserService targetUserService = new UserService();Enhancer enhancer = new Enhancer();enhancer.setSuperclass(UserService.class);//代理逻辑:1MethodInterceptor firstCallback = new MethodInterceptor() {@Overridepublic Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {System.out.println("before");Object result = method.invoke(targetUserService, args);System.out.println("after");return result;}};//代理逻辑:2NoOp secondCallback = NoOp.INSTANCE;enhancer.setCallbacks(new Callback[]{firstCallback, secondCallback});enhancer.setCallbackFilter(new CallbackFilter() {@Overridepublic int accept(Method method) {//方法test执行=》firstCallback代理逻辑:1if (method.getName().equals("test")) {return 0;}//其他执行=》secondCallback代理逻辑:2return 1;}});UserService proxyUserService = (UserService) enhancer.create();System.out.println("执行proxyUserService.test:");proxyUserService.test();System.out.println("--------------------------------------------------------");System.out.println("执行proxyUserService.a:");proxyUserService.a();}

最终执行效果:

执行proxyUserService.test:

before

userService execute test....

after

--------------------------------------------------------

执行proxyUserService.a:

userService execute a....

JDK动态代理

JDK动态代理是利用反射机制生成一个实现代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理。

使用示例-支持创建代理对象,执行代理逻辑

java">//接口
public interface UserInterface {void test();void a();
}
//实现类
public class UserService implements UserInterface {@Overridepublic void test() {System.out.println("userService execute test....");}@Overridepublic void a() {System.out.println("userService execute a....");}
}

使用Proxy.newProxyInstance创建一个代理接口,InvocationHandler制定代理逻辑

java">public class CylTest {public static void main(String[] args) {UserService targetUserService = new UserService();UserInterface proxyUserInterface = (UserInterface) Proxy.newProxyInstance(UserInterface.class.getClassLoader(),new Class[]{UserInterface.class},new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("before");Object result = method.invoke(targetUserService, args);System.out.println("after");return result;}});proxyUserInterface.test();}
}

最终执行效果:

before

userService execute test....

after

ProxyFactory

如何自动在CGLIB和JDK动态代理转换

ProxyFactory是Spring封装的代理工厂,对目标对象使用CGLIB或者JDK动态代理有处理逻辑。

代理方式
CGLIBisProxyTargetClass属性=true
只实现了SpringProxy接口
被代理对象没有实现接口
JDK动态代理被代理类只实现了接口,且实现了非SpringProxy接口

org.springframework.aop.framework.DefaultAopProxyFactory#createAopProxy

java">@Overridepublic AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {// 如果ProxyFactory的isOptimize为true,Spring认为cglib比jdk动态代理要快// 或者isProxyTargetClass为true,// 或者被代理对象没有实现接口,// 或者只实现了SpringProxy这个接口// 那么则利用Cglib进行动态代理,但如果被代理类是接口,或者被代理类已经是进行过JDK动态代理而生成的代理类了则只能进行JDK动态代理// 其他情况都会进行JDK动态代理,比如被代理类实现了除SpringProxy接口之外的其他接口// 是不是在GraalVM虚拟机上运行if (!NativeDetector.inNativeImage() &&(config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config))) {Class<?> targetClass = config.getTargetClass();if (targetClass == null) {throw new AopConfigException("TargetSource cannot determine target class: " +"Either an interface or a target is required for proxy creation.");}if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {return new JdkDynamicAopProxy(config);}return new ObjenesisCglibAopProxy(config);}else {return new JdkDynamicAopProxy(config);}}

使用示例-使用CGLIB代理方式

设置目标类 

java">public class UserService {public void test() {System.out.println("test...");}}
java">public static void main(String[] args) {UserService userService = new UserService();ProxyFactory proxyFactory = new ProxyFactory();//proxyFactory.setTarget(userService);//代理逻辑1MethodBeforeAdvice methodBeforeAdvice = new MethodBeforeAdvice() {@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println("begin");}};//代理逻辑2AfterReturningAdvice afterReturningAdvice = new AfterReturningAdvice() {@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println("end");}};//添加多个代理逻辑proxyFactory.addAdvice(0, methodBeforeAdvice);proxyFactory.addAdvice(1, afterReturningAdvice);UserService proxyUserService = (UserService) proxyFactory.getProxy();proxyUserService.test();}

使用示例-使用JDK动态代理方式

设置目标接口

java">//UserInterface
public interface UserInterface {void test();
}//UserService
public class UserService implements UserInterface {@Overridepublic void test() {System.out.println("test...");}
}
java">public static void main(String[] args) {UserService userService = new UserService();ProxyFactory proxyFactory = new ProxyFactory();proxyFactory.setTarget(userService);proxyFactory.setInterfaces(UserInterface.class);//代理逻辑1MethodBeforeAdvice methodBeforeAdvice = new MethodBeforeAdvice() {@Overridepublic void before(Method method, Object[] args, Object target) throws Throwable {System.out.println("begin");}};//代理逻辑2AfterReturningAdvice afterReturningAdvice = new AfterReturningAdvice() {@Overridepublic void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {System.out.println("end");}};//添加多个代理逻辑proxyFactory.addAdvice(0, methodBeforeAdvice);proxyFactory.addAdvice(1, afterReturningAdvice);UserInterface proxyUserService = (UserInterface) proxyFactory.getProxy();proxyUserService.test();
}


http://www.ppmy.cn/embedded/6968.html

相关文章

MongoDB的使用

一、Spring Boot集成MongoDB 1 引用依赖包 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency> 2 配置文件配置mongodb资料 # MongoDB连接信息 spring.…

存储竞赛,角逐未来

随着人工智能&#xff08;AI&#xff09;和大数据驱动的海量数据需求&#xff0c;对存储技术的要求也在不断提高。在此背景下&#xff0c;各大存储芯片巨头之间的技术竞赛日益激烈。 在NAND闪存领域&#xff0c;企业关注的重点在于层数的突破。近日&#xff0c;《韩国经济日报》…

Meta通过开源Llama 3 LLM提高了标准

Meta 推出了 Llama 3,这是其最先进的开源大型语言模型(LLM)的下一代产品。这家科技巨头声称,Llama 3 在现实场景中建立了新的性能基准,超越了之前行业领先的模型,如 GPT-3.5。 Meta 在一篇博文中宣布了这一发布,并表示:"通过 Llama 3,我们致力于打造与当今最好的专有模型…

上位机图像处理和嵌入式模块部署(树莓派4b和驱动的编写)

【 声明&#xff1a;版权所有&#xff0c;欢迎转载&#xff0c;请勿用于商业用途。 联系信箱&#xff1a;feixiaoxing 163.com】 树莓派4b上面还支持驱动代码的编写&#xff0c;这是我没有想到的。这里驱动&#xff0c;更多的是一种框架的编写&#xff0c;不一定是编写真正的驱…

c++二分排序(向右

描述 给出有 n 个元素的由小到大的序列&#xff0c;请你编程找出某元素最后一次出现的位置。 (n<10^6 输入描述 第一行&#xff1a;一个整数&#xff0c;表示由小到大序列元素个数&#xff1b;下面 n 行&#xff0c;每行一个整数&#xff1b; 最后一行 一个整数 x&#x…

iOS知识点---Runloop

iOS 中的 Runloop 机制是一种事件驱动模型&#xff0c;用于管理和调度线程上的事件&#xff0c;确保线程在有工作要做时保持活跃&#xff0c;无事可做时进入休眠状态以节省系统资源。以下是 Runloop 机制的关键组成部分及其工作原理&#xff1a; 关键组成部分与原理&#xff1…

基于springboot实现智能物流管理系统设计项目【项目源码+论文说明】

基于springboot实现智能物流管理系统演示 摘要 随着信息技术在管理上越来越深入而广泛的应用&#xff0c;管理信息系统的实施在技术上已逐步成熟。本文介绍了智能物流管理系统的开发全过程。通过分析智能物流管理系统管理的不足&#xff0c;创建了一个计算机管理智能物流管理系…

ES6 全详解 let 、 const 、解构赋值、剩余运算符、函数默认参数、扩展运算符、箭头函数、新增方法,promise、Set、class等等

目录 ES6概念ECMAScript6简介ECMAScript 和 JavaScript 的关系ES6 与 ECMAScript 2015 的关系 1、let 、 const 、var 区别2、变量解构赋值1、数组解构赋值2、对象解构赋值3、字符串的解构赋值 3、展开剩余运算符1、**展开运算符(...)**2、**剩余运算符(...)** 4、函数的拓展函…