Spring动态代理原理
1.JDK实现动态代理 (基于接口)
ClassLoader: 类加载器
InterFaces: 获取与原始类相同的接口
InvocationHandler: 额外功能
//底层创建代理对象
Proxy.newProxyInstance(ClassLoader,InterFaces, InvocationHandler);
package com.baizhi.原理;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class TestJDK {
@Test
public void testJDK(){
final UserService userService=new UserServiceImpl();
//获取到原始类实现的接口
Class<?>[] interfaces = userService.getClass().getInterfaces();
//创建额外功能
InvocationHandler invocationHandler = new InvocationHandler() {
//返回值 Object 原始方法的返回值
@Override //原始类对象 原始方法 原始方法的参数
public Object invoke(Object target, Method method, Object[] args) throws Throwable {
System.out.println("原始方法执行之前执行的功能");
//调用原始方法 原始方法的返回值
Object ret = method.invoke(userService, args);
System.out.println("原始方法执行之后执行的功能");
return ret;
}
};
//创建动态代理对象 //借类加载器 //相同的接口 //额外功能
UserService proxy=(UserService) Proxy.newProxyInstance(TestJDK.class.getClassLoader(), interfaces, invocationHandler);
proxy.register();
}
}
2.CGLIB实现动态代理(基于父子类继承关系)
package com.baizhi.原理;
import org.junit.Test;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import java.lang.reflect.Method;
public class TestCGLIB {
@Test
public void testCglib(){
//原始类对象
final UserService userService= new UserServiceImpl();
//额外功能
InvocationHandler invocationHandler = new InvocationHandler() {
/*
* 返回值 代表调用原始方法的返回值
*
* */
@Override //原始类对象 原始方法 调用原始方法的参数
public Object invoke(Object o, Method method, Object[] args) throws Throwable {
System.out.println("原始方法执行之前执行");
//调用原始方法
Object ret = method.invoke(userService, args);
System.out.println("原始方法执行之后执行");
return ret;
}
};
//创建enhancer对象
Enhancer enhancer = new Enhancer();
//设置类加载器
enhancer.setClassLoader(TestCGLIB.class.getClassLoader());
//把原始类作为父类 保证原始类与代理类拥有相同的方法
enhancer.setSuperclass(userService.getClass());
//设置额外功能
enhancer.setCallback(invocationHandler);
//创建代理对象
UserServiceImpl userService1 =(UserServiceImpl)enhancer.create();
userService1.register();
}
}
Spring默认的动态代理方式: JDK动态代理
proxy-target-class=“false” 默认值为false JDK动态代理
“true” 默认值为true CGLIB代理