掘金 后端 ( ) • 2024-04-23 11:07

Spring5深入浅出篇:AOP底层实现原理

很多粉丝私信我这个Spring5的课程在哪看,这边是在B站免费观看欢迎大家投币支持一下. https://www.bilibili.com/video/BV1hK411Y7zf

核⼼问题

1. AOP如何创建动态代理类(动态字节码技术)
2. Spring⼯⼚如何加⼯创建代理对象
 通过原始对象的id值,获得的是代理对象

动态代理类的创建

JDK的动态代理

  • Proxy.newProxyInstance⽅法参数详解 image.png

image.png

  • 编码
public class TestJDKProxy {
 /*
 1. 借⽤类加载器 TestJDKProxy
 UserServiceImpl
 2. JDK8.x前
 final UserService userService = new UserServiceImpl();
 */
 public static void main(String[] args) {
 //1 创建原始对象
 UserService userService = new UserServiceImpl();
 //2 JDK创建动态代理
 InvocationHandler handler = new InvocationHandler(){
 @Override
 public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
 System.out.println("------proxy log --------");
 //原始⽅法运⾏
 Object ret = method.invoke(userService, args);
 return ret;
 }
 };
 UserService userServiceProxy =(UserService)Proxy.newProxyInstance(UserServiceImpl.class.getClassLoader(),userService.getClass().getInterfaces(),handler);
 userServiceProxy.login("suns", "123456");
 userServiceProxy.register(new User());
 }
}

CGlib的动态代理

CGlib创建动态代理的原理:⽗⼦继承关系创建代理对象,原始类作为⽗类,代理类作为⼦类,这样既可以保证2者⽅法⼀致,同时在代理类中提供新的实现(额外功能+原始⽅法)

image.png

  • CGlib编码
package com.baizhiedu.cglib;
import com.baizhiedu.proxy.User;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class TestCglib {
 public static void main(String[] args) {
 //1 创建原始对象
 UserService userService = new UserService();
 /*
 2 通过cglib⽅式创建动态代理对象
 
Proxy.newProxyInstance(classloader,interface,invocationhandler)
 Enhancer.setClassLoader()
 Enhancer.setSuperClass()
 Enhancer.setCallback(); ---> MethodInterceptor(cglib)
 Enhancer.create() ---> 代理
 */
 Enhancer enhancer = new Enhancer();
 enhancer.setClassLoader(TestCglib.class.getClassLoader());
 enhancer.setSuperclass(userService.getClass());
 MethodInterceptor interceptor = new MethodInterceptor() {
 //等同于 InvocationHandler --- invoke
 @Override
 public Object intercept(Object o, Method method,Object[] args, MethodProxy methodProxy) throws Throwable {
 	System.out.println("---cglib log----");
 	Object ret = method.invoke(userService, args);
 	return ret;
  }
 };
 	enhancer.setCallback(interceptor);
 	UserService userServiceProxy = (UserService)
	enhancer.create();
 	userServiceProxy.login("suns", "123345");
 	userServiceProxy.register(new User());
 }
}

总结

JDK动态代理 Proxy.newProxyInstance() 通过接⼝创建代理的实现类

Cglib动态代理 Enhancer 通过继承⽗类创建的代理类

以上便是本文的全部内容,我是全干程序员demo,每天为你带来最新好用的开发运维工具,如果你觉得用,请点赞,让更多的人了解相关工具

如果你想了解更多关于全干程序员demo,还有更多付费工具免费破解如JB全家桶,可以关注公众号-全干程序员demo,后面文章会首先同步至公众号