AOP的底层实现原理

1、核心问题

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

2、动态代理类的创建

2.1JDK的动态代理
Proxy.newProxyInstance方法参数详解
在这里插入图片描述

编码:
public class TestJDKProxy {
public static void main(String[] args) {
//1、创建原始对象
final UserService userService = new UserServiceImpl();
//2、创建动态代理
InvocationHandler handler = new InvocationHandler() {
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(TestJDKProxy.class.getClassLoader(),userService.getClass().getInterfaces(),handler);
userServiceProxy.login(“chai”,“2334”);
userServiceProxy.register(new User());
}
}

2.2CGlib的动态代理
CGlib 创建动态代理的原理:父子继承关系创建代理对象,原始类作为父类,代理类作为子类,这样可以保证二者的方法一致,同时,在代理类中提供新的实现(额外功能+原始方法)
在这里插入图片描述
编码
package com.chai.cglib;

import com.chai.pojo.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(final String[] args) {
//1、创建原始对象
final UserService userService = new UserService();

    2、通过cglib方式创建动态代理对象
    jdk:    proxy.newProxyInstance(classLoader,Interface,invocatonHandler);
    Enhancer.serClassLoader();
    Enhancer.serSuperClass();
    Enhancer.setCallback();----->MethodInterceptor(cglib)  就相当于invocationHandler
    Enhancer.create()-------->创建代理对象

    Enhancer enhancer = new Enhancer();
    enhancer.setClassLoader(TestCglib.class.getClassLoader());
    enhancer.setSuperclass(userService.getClass());
    MethodInterceptor interceptor = new MethodInterceptor() {
        public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
            System.out.println("--cglib--log---");
            Object ret = method.invoke(userService, objects);
            return ret;
        }
    };
    enhancer.setCallback(interceptor);
    UserService userServiceProxy = (UserService) enhancer.create();
     userServiceProxy.login("ccc","ssss");
     userServiceProxy.register(new User());

}

}

总结:
JDK动态代理: Proxy.newProxyInstance() 通过接口创建代理的实现类
cglib动态代理: Enhancer 通过继承父类 创建的代理类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值