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 通过继承父类 创建的代理类