1、博客内容均出自于咕泡学院架构师第三期
2、架构师系列内容:架构师学习笔记(持续更新)
0、代理模式(Proxy Pattern)
指为其他对象提供一种代理,以控制对这个对象的访问。代理对象在客户端和目标对象之间起到中介作用。属于结构型设计模式。
使用目的:
- 保护目标对象
- 增强目标对象
代理模式分为静态代理,动态代理:
- 静态代理只能通过手动完成代理操作,如果被代理类增加新的方法,代理类需要同步新增,违背开闭原则。
- 动态代理采用在运行时动态生成代码的方式,取消了对被代理类的扩展限制,遵循开闭原则。
- 若动态代理要对目标类的增强逻辑扩展,结合策略模式,只需要新增策略类便可完成,无需修改代理类的代码。
代理模式的优缺点:
优点:
- 代理模式能将代理对象与真实被调用的目标对象分离。
- 一定程度上降低了系统的耦合度,扩展性好。
- 可以起到保护目标对象的作用。
- 可以对目标对象的功能增强。
缺点:
- 代理模式会造成系统设计中类的数量增加。
- 在客户端和目标对象增加一个代理对象,会造成请求处理速度变慢。
- 增加了系统的复杂度。
实际体现:
比如:租房中介,售票黄牛,婚介,经纪人,快递,事务代理,非侵入式日志监听等,都是代理模式的实际体现。
这是一个代理模式的类结构图:
Subject 是顶层接口,RealSubject是真实对象(被代理对象),Proxy是代理对象,代理对象持有被代理对象的引用,客户端调用代理对象方法,同时也调用被代理对象的方法,但是在代理对象前后增加一些处理。
在代码中,代理就是一段代码增强,在原本逻辑前后增加一些逻辑,而调用者无感知。
1、静态代理
优缺点:
优点:
- 业务类只需要关注业务逻辑本身,保证了业务类的重用性。这是代理模式的共有优点。
缺点:
- 代理对象的一个接口只服务于一种类型的对象,如果要代理的类型很多,势必要为每一种类型的方法都进行代理,静态代理在程序规模稍大时就无法胜任了。
- 如果接口增加一个方法,除了所有实现类需要实现这个方法外,所有代理类也需要实现此方法。显而易见,增加了代码维护的复杂度。
简单实现:
人到适婚年龄,父母总是迫不及待希望早点抱孙子。而现在社会的人在各种压力之下,都选择晚婚晚育。于是着急的父母就开始到处为自己的子女相亲,比子女自己还着急。这个相亲的过程,就是一种代理模式。
首先创建Person:
package com.jarvisy.demo.pattern.proxy;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:32
* @description :人有很多行为,要谈恋爱,要住房子,要购物,要工作
*/
public interface Person {
public void findLove();
}
儿子要找对象,实现 Son 类:
package com.jarvisy.demo.pattern.proxy.staticproxy;
import com.jarvisy.demo.pattern.proxy.Person;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:33
* @description :
*/
public class Son implements Person {
@Override
public void findLove() {
//我没有时间
//工作忙
System.out.println("儿子要求:肤白貌美大长腿");
}
}
父亲要帮儿子相亲,实现 Father 类:
package com.jarvisy.demo.pattern.proxy.staticproxy;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:34
* @description :
*/
public class Father {
private Son son;
public Father(Son son) {
this.son = son;
}
//目标对象的引用给拿到
public void findLove() {
System.out.println("父亲物色对象");
this.son.findLove();
System.out.println("双方父母同意,确立关系");
}
}
测试代码:
package com.jarvisy.demo.pattern.proxy.staticproxy;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:41
* @description :
*/
public class FatherProxyTest {
public static void main(String[] args) {
//只能帮儿子找对象,不能帮表妹,陌生人找对象
Father father = new Father(new Son());
father.findLove();
}
}
再来一个实际业务场景:
在分布业务场景中,通常会对数据库进行分库分表,分库分表之后使用Java操作时,就可能需要配置多个数据源,我们通过设置数据源路由来动态切换数据源。
首先创建Order订单实体:
package com.jarvisy.demo.pattern.proxy.dbroute;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:51
* @description :
*/
public class Order {
private Object orderInfo;
//订单创建时间进行按年分库
private Long createTime;
private String id;
public Object getOrderInfo() {
return orderInfo;
}
public void setOrderInfo(Object orderInfo) {
this.orderInfo = orderInfo;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
创建OrderDao持久层操作类:
package com.jarvisy.demo.pattern.proxy.dbroute;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:52
* @description :
*/
public class OrderDao {
public int insert(Order order) {
System.out.println("OrderDao创建Order成功!");
return 1;
}
}
创建IOrderService接口:
package com.jarvisy.demo.pattern.proxy.dbroute;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:53
* @description :
*/
public interface IOrderService {
int createOrder(Order order);
}
创建OrderService实现类:
package com.jarvisy.demo.pattern.proxy.dbroute;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:54
* @description :
*/
public class OrderService implements IOrderService {
private OrderDao orderDao;
public OrderService() {
//如果使用Spring应该是自动注入的
//为了使用方便,在构造方法中将orderDao直接初始化了
orderDao = new OrderDao();
}
public int createOrder(Order order) {
System.out.println("OrderService调用orderDao创建订单");
return orderDao.insert(order);
}
}
接下来使用静态代理,主要完成的功能是:根据订单创建时间自动按年进行分库,根据开闭原则,原来写好的逻辑不去修改,通过代理对象来完成。
先创建数据源路由对象,使用ThreadLocal的单例实现。
DynamicDataSourceEntry 类:
package com.jarvisy.demo.pattern.proxy.dbroute.db;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 19:58
* @description :
*/
public class DynamicDataSourceEntity {
public final static String DEFAULT_SOURCE = null;
private final static ThreadLocal<String> local = new ThreadLocal<String>();
private DynamicDataSourceEntity() {
}
/**
* 清空数据源
*/
public static void clear() {
local.remove();
}
/**
* 获取当前正在使用的数据源名字
*
* @return
*/
public static String get() {
return local.get();
}
/**
* 还原当前切面的数据源
*/
public static void restore() {
local.set(DEFAULT_SOURCE);
}
/**
* 设置已知名字的数据源
*
* @param source
*/
public static void set(String source) {
local.set(source);
}
/**
* 根据年份动态设置数据源
*
* @param year
*/
public static void set(int year) {
local.set("DB_" + year);
}
}
创建切换数据源的代理OrderServiceStaticProxy类:
package com.jarvisy.demo.pattern.proxy.dbroute.proxy;
import com.jarvisy.demo.pattern.proxy.dbroute.IOrderService;
import com.jarvisy.demo.pattern.proxy.dbroute.Order;
import com.jarvisy.demo.pattern.proxy.dbroute.db.DynamicDataSourceEntity;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:02
* @description :
*/
public class OrderServiceStaticProxy implements IOrderService {
private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
private IOrderService orderService;
public OrderServiceStaticProxy(IOrderService orderService) {
this.orderService = orderService;
}
public int createOrder(Order order) {
Long time = order.getCreateTime();
Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
System.out.println("静态代理类自动分配到【DB_" + dbRouter + "】数据源处理数据");
DynamicDataSourceEntity.set(dbRouter);
this.orderService.createOrder(order);
DynamicDataSourceEntity.restore();
return 0;
}
}
测试代码:
package com.jarvisy.demo.pattern.proxy.dbroute;
import com.jarvisy.demo.pattern.proxy.dbroute.proxy.OrderServiceStaticProxy;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:06
* @description :
*/
public class DbRouteProxyTest {
public static void main(String[] args) {
try {
Order order = new Order();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date = sdf.parse("2020/09/20");
order.setCreateTime(date.getTime());
IOrderService orderService = new OrderServiceStaticProxy(new OrderService());
orderService.createOrder(order);
} catch (Exception e) {
e.printStackTrace();
}
}
}
类图结构:
2、动态代理
动态代理和静态对比基本思路是一致的,只不过动态代理功能更加强大,随着业务的扩展适应性更强。
还以找对象为例,使用动态代理相当于是能够适应复杂的业务场景。不仅仅只是父亲给儿子找对象,如果找对象这项业务发展成了一个产业,进而出现了媒婆、婚介所等这样的形式。那么,此时用静态代理成本就更大了,需要一个更加通用的解决方案,要满足任何单身人士找对象的需求。
我们升级一下代码,先来看 JDK 实现方式。
JDK 实现方式:
创建媒婆(婚介)JDKMeipo 类:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.jdkproxy;
import com.jarvisy.demo.pattern.proxy.Person;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:44
* @description :
*/
public class JDKMeipo implements InvocationHandler {
private Person target;
public Object getInstance(Person target) throws Exception {
this.target = target;
Class<?> clazz = target.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object obj = method.invoke(this.target, args);
after();
return obj;
}
private void before() {
System.out.println("我是媒婆,我要给你找对象,现在已经确认你的需求");
System.out.println("开始物色");
}
private void after() {
System.out.println("OK的话,准备办事");
}
}
创建单身客户Customer类:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.jdkproxy;
import com.jarvisy.demo.pattern.proxy.Person;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:45
* @description :
*/
public class Customer implements Person {
public void findLove() {
System.out.println("高富帅");
System.out.println("身高180cm");
System.out.println("有6块腹肌");
}
}
测试代码:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.jdkproxy;
import com.jarvisy.demo.pattern.proxy.Person;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:46
* @description :
*/
public class JDKProxyTest {
public static void main(String[] args) {
try {
Person obj = (Person) new JDKMeipo().getInstance(new Customer());
obj.findLove();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我们再来改造用静态代理写的数据源动态路由的例子:
创建动态代理的类 OrderServiceDynamicProxy:
package com.jarvisy.demo.pattern.proxy.dbroute.proxy;
import com.jarvisy.demo.pattern.proxy.dbroute.db.DynamicDataSourceEntity;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:54
* @description :
*/
public class OrderServiceDynamicProxy implements InvocationHandler {
private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
Object proxyObj;
public Object getInstance(Object proxyObj) {
this.proxyObj = proxyObj;
Class<?> clazz = proxyObj.getClass();
return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before(args[0]);
Object object = method.invoke(proxyObj, args);
after();
return object;
}
private void after() {
System.out.println("Proxy after method");
//还原成默认的数据源
DynamicDataSourceEntity.restore();
}
//target 应该是订单对象Order
private void before(Object target) {
try {
//进行数据源的切换
System.out.println("Proxy before method");
//约定优于配置
Long time = (Long) target.getClass().getMethod("getCreateTime").invoke(target);
Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
System.out.println("静态代理类自动分配到【DB_" + dbRouter + "】数据源处理数据");
DynamicDataSourceEntity.set(dbRouter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
测试类修改:
package com.jarvisy.demo.pattern.proxy.dbroute;
import com.jarvisy.demo.pattern.proxy.dbroute.proxy.OrderServiceDynamicProxy;
import com.jarvisy.demo.pattern.proxy.dbroute.proxy.OrderServiceStaticProxy;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:06
* @description :
*/
public class DbRouteProxyTest {
/*public static void main(String[] args) {
try {
Order order = new Order();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date = sdf.parse("2020/09/20");
order.setCreateTime(date.getTime());
IOrderService orderService = new OrderServiceStaticProxy(new OrderService());
orderService.createOrder(order);
} catch (Exception e) {
e.printStackTrace();
}
}*/
public static void main(String[] args) {
try {
Order order = new Order();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date date = sdf.parse("2020/09/20");
order.setCreateTime(date.getTime());
IOrderService orderService = (IOrderService) new OrderServiceDynamicProxy().getInstance(new OrderService());
orderService.createOrder(order);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用动态代理实现后,我们不仅能够实现Order的数据源动态路由,还可以实现其他任何类的数据源路由。
当然,有比较重要的约定,必须要 求实现 getCreateTime()方法,因为路由规则是根据时间来运算的。这个可以通过接口规范来达到约束的目的。
通过以上的例子我们知道JDK Proxy代理类的步骤:
- 拿到被代理对象的引用,并且获取到它的所有的接口,反射获取(必须实现接口,jdk只能代理接口 由于java的单继承,动态生成的代理类已经继承了Proxy类的,就不能再继承其他的类,所以只能靠实现被代理类的接口的形式,故JDK的动态代理必须有接口)。
- JDK Proxy 类重新生成一个新的类、同时新的类要实现被代理类所有实现的所有的接口。
- 动态生成 Java 代码,把新加的业务逻辑方法由一定的逻辑代码去调用(在代码中体现)。
- 编译新生成的 Java 代码.class。
- 再重新加载到 JVM 中运行。
这个过程叫做字节码重组。JDK中有个规范,在ClassPath只要是 $开头的 class文件一般都是自动生成的。
那么我们有没有办法看到代替后的对象的真容呢?做一个这样测试,我们从内存中的对象字节码通过文件流输出到一个新的 class 文件,然后,利用反编译工具jad查看 class 的源代码。
反编译工具jad使用请看https://blog.csdn.net/weixin_38024782/article/details/108701627
来看测试代码:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.jdkproxy;
import com.jarvisy.demo.pattern.proxy.Person;
import sun.misc.ProxyGenerator;
import java.io.FileOutputStream;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 20:46
* @description :
*/
public class JDKProxyTest {
public static void main(String[] args) {
try {
Person obj = (Person) new JDKMeipo().getInstance(new Customer());
obj.findLove();
byte [] bytes = ProxyGenerator.generateProxyClass("$Proxy0",new Class[]{Person.class});
FileOutputStream os = new FileOutputStream("E://$Proxy0.class");
os.write(bytes);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行之后,我们能在 E://盘下找到一个$Proxy0.class 文件。使用 Jad 反编译,得到$Proxy0.jad 文件,打开可以看到如下内容:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
import com.jarvisy.demo.pattern.proxy.Person;
import java.lang.reflect.*;
public final class $Proxy0 extends Proxy
implements Person
{
public $Proxy0(InvocationHandler invocationhandler)
{
super(invocationhandler);
}
public final boolean equals(Object obj)
{
try
{
return ((Boolean)super.h.invoke(this, m1, new Object[] {
obj
})).booleanValue();
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final void findLove()
{
try
{
super.h.invoke(this, m3, null);
return;
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final String toString()
{
try
{
return (String)super.h.invoke(this, m2, null);
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
public final int hashCode()
{
try
{
return ((Integer)super.h.invoke(this, m0, null)).intValue();
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m0;
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
Class.forName("java.lang.Object")
});
m3 = Class.forName("com.jarvisy.demo.pattern.proxy.Person").getMethod("findLove", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
}
catch(NoSuchMethodException nosuchmethodexception)
{
throw new NoSuchMethodError(nosuchmethodexception.getMessage());
}
catch(ClassNotFoundException classnotfoundexception)
{
throw new NoClassDefFoundError(classnotfoundexception.getMessage());
}
}
}
发现$Proxy0 继承了 Proxy 类,同时还实现了我们的 Person 接口,而且重写了findLove()等方法。而且在静态块中用反射查找到了目标对象的所有方法,而且保存了所有方法的引用,在重写的方法用反射调用目标对象的方法。这些都是 JDK 帮我们自动生成的。
知道这些后,自己动手写动态生成源代码,动态完成编译,替换JDK的代理:
模拟JDK代理:
创建 MyInvocationHandler 接口:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.myproxy;
import java.lang.reflect.Method;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:17
* @description :
*/
public interface MyInvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
创建MyClassLoader 类:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.myproxy;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:19
* @description :
*/
public class MyClassLoader extends ClassLoader {
private File classPathFile;
public MyClassLoader() {
String classPath = MyClassLoader.class.getResource("").getPath();
this.classPathFile = new File(classPath);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
String className = MyClassLoader.class.getPackage().getName() + "." + name;
if (classPathFile != null) {
File classFile = new File(classPathFile, name.replaceAll("\\.", "/") + ".class");
if (classFile.exists()) {
FileInputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(classFile);
out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
return defineClass(className, out.toByteArray(), 0, out.size());
} catch (Exception e) {
e.printStackTrace();
}
}
}
return null;
}
}
创建 MyProxy 类:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.myproxy;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:18
* @description :用来生成源代码的工具类
*/
public class MyProxy {
public static final String ln = "\r\n";
public static Object newProxyInstance(MyClassLoader classLoader, Class<?>[] interfaces, MyInvocationHandler h) {
try {
//1、动态生成源代码.java文件
String src = generateSrc(interfaces);
// System.out.println(src);
//2、Java文件输出磁盘
String filePath = MyProxy.class.getResource("").getPath();
// System.out.println(filePath);
File f = new File(filePath + "$Proxy0.java");
FileWriter fw = new FileWriter(f);
fw.write(src);
fw.flush();
fw.close();
//3、把生成的.java文件编译成.class文件
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager manage = compiler.getStandardFileManager(null, null, null);
Iterable iterable = manage.getJavaFileObjects(f);
JavaCompiler.CompilationTask task = compiler.getTask(null, manage, null, null, null, iterable);
task.call();
manage.close();
//4、编译生成的.class文件加载到JVM中来
Class proxyClass = classLoader.findClass("$Proxy0");
Constructor c = proxyClass.getConstructor(MyInvocationHandler.class);
f.delete();
//5、返回字节码重组以后的新的代理对象
return c.newInstance(h);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String generateSrc(Class<?>[] interfaces) {
StringBuffer sb = new StringBuffer();
sb.append("package com.jarvisy.demo.pattern.proxy.dynamicproxy.myproxy;" + ln);
sb.append("import com.jarvisy.demo.pattern.proxy.Person;" + ln);
sb.append("import java.lang.reflect.*;" + ln);
sb.append("public class $Proxy0 implements " + interfaces[0].getName() + "{" + ln);
sb.append("MyInvocationHandler h;" + ln);
sb.append("public $Proxy0(MyInvocationHandler h) { " + ln);
sb.append("this.h = h;");
sb.append("}" + ln);
for (Method m : interfaces[0].getMethods()) {
Class<?>[] params = m.getParameterTypes();
StringBuffer paramNames = new StringBuffer();
StringBuffer paramValues = new StringBuffer();
StringBuffer paramClasses = new StringBuffer();
for (int i = 0; i < params.length; i++) {
Class clazz = params[i];
String type = clazz.getName();
String paramName = toLowerFirstCase(clazz.getSimpleName());
paramNames.append(type + " " + paramName);
paramValues.append(paramName);
paramClasses.append(clazz.getName() + ".class");
if (i > 0 && i < params.length - 1) {
paramNames.append(",");
paramClasses.append(",");
paramValues.append(",");
}
}
sb.append("public " + m.getReturnType().getName() + " " + m.getName() + "(" + paramNames.toString() + ") {" + ln);
sb.append("try{" + ln);
sb.append("Method m = " + interfaces[0].getName() + ".class.getMethod(\"" + m.getName() + "\",new Class[]{" + paramClasses.toString() + "});" + ln);
sb.append((hasReturnValue(m.getReturnType()) ? "return " : "") + getCaseCode("this.h.invoke(this,m,new Object[]{" + paramValues + "})", m.getReturnType()) + ";" + ln);
sb.append("}catch(Error _ex) { }");
sb.append("catch(Throwable e){" + ln);
sb.append("throw new UndeclaredThrowableException(e);" + ln);
sb.append("}");
sb.append(getReturnEmptyCode(m.getReturnType()));
sb.append("}");
}
sb.append("}" + ln);
return sb.toString();
}
private static Map<Class, Class> mappings = new HashMap<Class, Class>();
static {
mappings.put(int.class, Integer.class);
}
private static String getReturnEmptyCode(Class<?> returnClass) {
if (mappings.containsKey(returnClass)) {
return "return 0;";
} else if (returnClass == void.class) {
return "";
} else {
return "return null;";
}
}
private static String getCaseCode(String code, Class<?> returnClass) {
if (mappings.containsKey(returnClass)) {
return "((" + mappings.get(returnClass).getName() + ")" + code + ")." + returnClass.getSimpleName() + "Value()";
}
return code;
}
private static boolean hasReturnValue(Class<?> clazz) {
return clazz != void.class;
}
private static String toLowerFirstCase(String src) {
char[] chars = src.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
}
创建MyMeipo类:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.myproxy;
import java.lang.reflect.Method;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:22
* @description :
*/
public class MyMeipo implements MyInvocationHandler {
private Object target;
public Object getInstance(Object target) throws Exception {
this.target = target;
Class<?> clazz = target.getClass();
return MyProxy.newProxyInstance(new MyClassLoader(), clazz.getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
before();
Object obj = method.invoke(this.target, args);
after();
return obj;
}
private void before() {
System.out.println("我是媒婆,我要给你找对象,现在已经确认你的需求");
System.out.println("开始物色");
}
private void after() {
System.out.println("OK的话,准备办事");
}
}
测试代码:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.myproxy;
import com.jarvisy.demo.pattern.proxy.Person;
import com.jarvisy.demo.pattern.proxy.dynamicproxy.jdkproxy.Customer;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:25
* @description :
*/
public class MyProxyTest {
public static void main(String[] args) {
try {
//JDK动态代理的实现原理
// 这里改用自己写的Proxy类
Person obj = (Person) new MyMeipo().getInstance(new Customer());
System.out.println(obj.getClass());
obj.findLove();
} catch (Exception e) {
e.printStackTrace();
}
}
}
简单模拟jdk动态代理就完成了。
3、JDK动态代理问题
1、为何调用代理类的方法就会自动进入InvocationHandler 的 invoke()方法呢?
其实是因为在动态代理类的定义中,构造函数是含参的构造,参数就是我们invocationHandler 实例,而每一个被代理接口的方法都会在代理类中生成一个对应的实现方法,并在实现方法中最终调用invocationHandler 的invoke方法,这就解释了为何执行代理类的方法会自动进入到我们自定义的invocationHandler的invoke方法中,然后在我们的invoke方法中再利用jdk反射的方式去调用真正的被代理类的业务方法,而且还可以在方法的前后去加一些我们自定义的逻辑。比如切面编程AOP等。
2、为什么被代理类要实现接口
由于java的单继承,动态生成的代理类已经继承了Proxy类的,就不能再继承其他的类,所以只能靠实现被代理类的接口的形式,故JDK的动态代理必须有接口
相关博客:https://blog.csdn.net/u014301265/article/details/102832131
3、为什么JDK动态代理中要求目标类实现的接口数量不能超过65535个
先明确几个概念:
Class文件是一组以8字节为基础单位的二进制流
各个数据项目严格按照顺序紧凑排列在class文件中
中间没有任何分隔符,这使得class文件中存储的内容几乎是全部程序运行的程序
Java虚拟机规范规定,Class文件格式采用类似C语言结构体的伪结构来存储数据,这种结构只有两种数据类型:无符号数和表
接口索引计数器(interfaces_count),占2字节
参考第一句话:class文件是一组8字节为基础的二进制流,interface_count占2字节。也就是16.00000000,00000000 所以,证明
interface_count的数量最多是2^16次方 最大值=65535
这是在JVM的层面上决定了它的数量最多是65535
且在java源码中也可以看到
if (var2.size() > 65535) {
throw new IllegalArgumentException("interface limit exceeded: " var2.size());
直接做了65535的长度的校验,所以,JDK的动态代理要求,目标类实现的接口数量不能超过65535。
4、CGLib调用API及原理分析
CGLib 代理的目标对象不需要实现任何接口,它是通过动态继承目标对象实现的动态代理
简单看一下 CGLib 代理的使用,还是以媒婆为例,创建 CglibMeipo 类:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:34
* @description :
*/
public class CglibMeipo implements MethodInterceptor {
public Object getInstance(Class<?> clazz) throws Exception {
//相当于Proxy,代理的工具类
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
before();
Object obj = methodProxy.invokeSuper(o, objects);
after();
return obj;
}
private void before() {
System.out.println("我是媒婆,我要给你找对象,现在已经确认你的需求");
System.out.println("开始物色");
}
private void after() {
System.out.println("OK的话,准备办事");
}
}
测试代码:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:45
* @description :
*/
public class CglibTest {
public static void main(String[] args) {
try {
Customer obj = (Customer) new CglibMeipo().getInstance(Customer.class);
obj.findLove();
} catch (Exception e) {
e.printStackTrace();
}
}
}
5、CGLib的实现原理
我们可以在测试代码中加上一句代码,将 CGLib 代理后的 class 写入到磁盘,然后,我们再反编译一探究竟:
package com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy;
import org.springframework.cglib.core.DebuggingClassWriter;
/**
* @author :Jarvisy
* @date :Created in 2020/9/20 22:45
* @description :
*/
public class CglibTest {
public static void main(String[] args) {
try {
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "E://cglib_proxy_classes");
Customer obj = (Customer) new CglibMeipo().getInstance(Customer.class);
obj.findLove();
} catch (Exception e) {
e.printStackTrace();
}
}
}
重新执行代码,我们会发现在 E://cglib_proxy_class 目录下多了三个 class 文件
通过调试跟踪,我们发现 Customer$$EnhancerByCGLIB$$9d895b9.class 就是 CGLib 生成的代理类,继承了 Customer 类。反编译后代码是这样的:
部分代码已删除
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: <generated>
package com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy;
import java.lang.reflect.Method;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.cglib.core.Signature;
import org.springframework.cglib.proxy.*;
// Referenced classes of package com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy:
// Customer
public class Customer$$EnhancerByCGLIB$$9d895b9 extends Customer
implements Factory
{
static void CGLIB$STATICHOOK1()
{
Method amethod[];
Method amethod1[];
CGLIB$THREAD_CALLBACKS = new ThreadLocal();
CGLIB$emptyArgs = new Object[0];
Class class1 = Class.forName("com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy.Customer$$EnhancerByCGLIB$$9d895b9");
Class class2;
amethod = ReflectUtils.findMethods(new String[] {
"findLove", "()V"
}, (class2 = Class.forName("com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy.Customer")).getDeclaredMethods());
Method[] _tmp = amethod;
CGLIB$findLove$0$Method = amethod[0];
CGLIB$findLove$0$Proxy = MethodProxy.create(class2, class1, "()V", "findLove", "CGLIB$findLove$0");
amethod1 = ReflectUtils.findMethods(new String[] {
"equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"
}, (class2 = Class.forName("java.lang.Object")).getDeclaredMethods());
Method[] _tmp1 = amethod1;
CGLIB$equals$1$Method = amethod1[0];
CGLIB$equals$1$Proxy = MethodProxy.create(class2, class1, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$1");
CGLIB$toString$2$Method = amethod1[1];
CGLIB$toString$2$Proxy = MethodProxy.create(class2, class1, "()Ljava/lang/String;", "toString", "CGLIB$toString$2");
CGLIB$hashCode$3$Method = amethod1[2];
CGLIB$hashCode$3$Proxy = MethodProxy.create(class2, class1, "()I", "hashCode", "CGLIB$hashCode$3");
CGLIB$clone$4$Method = amethod1[3];
CGLIB$clone$4$Proxy = MethodProxy.create(class2, class1, "()Ljava/lang/Object;", "clone", "CGLIB$clone$4");
}
final void CGLIB$findLove$0()
{
super.findLove();
}
public final void findLove()
{
CGLIB$CALLBACK_0;
if(CGLIB$CALLBACK_0 != null) goto _L2; else goto _L1
_L1:
JVM INSTR pop ;
CGLIB$BIND_CALLBACKS(this);
CGLIB$CALLBACK_0;
_L2:
JVM INSTR dup ;
JVM INSTR ifnull 37;
goto _L3 _L4
_L3:
break MISSING_BLOCK_LABEL_21;
_L4:
break MISSING_BLOCK_LABEL_37;
this;
CGLIB$findLove$0$Method;
CGLIB$emptyArgs;
CGLIB$findLove$0$Proxy;
intercept();
return;
super.findLove();
return;
}
final boolean CGLIB$equals$1(Object obj)
{
return super.equals(obj);
}
final String CGLIB$toString$2()
{
return super.toString();
}
final Object CGLIB$clone$4()
throws CloneNotSupportedException
{
return super.clone();
}
protected final Object clone()
throws CloneNotSupportedException
{
CGLIB$CALLBACK_0;
if(CGLIB$CALLBACK_0 != null) goto _L2; else goto _L1
_L1:
JVM INSTR pop ;
CGLIB$BIND_CALLBACKS(this);
CGLIB$CALLBACK_0;
_L2:
JVM INSTR dup ;
JVM INSTR ifnull 37;
goto _L3 _L4
_L3:
this;
CGLIB$clone$4$Method;
CGLIB$emptyArgs;
CGLIB$clone$4$Proxy;
intercept();
return;
_L4:
return super.clone();
}
public static MethodProxy CGLIB$findMethodProxy(Signature signature)
{
String s = signature.toString();
s;
s.hashCode();
}
public static void CGLIB$SET_THREAD_CALLBACKS(Callback acallback[])
{
CGLIB$THREAD_CALLBACKS.set(acallback);
}
public static void CGLIB$SET_STATIC_CALLBACKS(Callback acallback[])
{
CGLIB$STATIC_CALLBACKS = acallback;
}
public Object newInstance(Callback acallback[])
{
CGLIB$SET_THREAD_CALLBACKS(acallback);
CGLIB$SET_THREAD_CALLBACKS(null);
return new Customer$$EnhancerByCGLIB$$9d895b9();
}
public Object newInstance(Callback callback)
{
CGLIB$SET_THREAD_CALLBACKS(new Callback[] {
callback
});
CGLIB$SET_THREAD_CALLBACKS(null);
return new Customer$$EnhancerByCGLIB$$9d895b9();
}
public Object newInstance(Class aclass[], Object aobj[], Callback acallback[])
{
CGLIB$SET_THREAD_CALLBACKS(acallback);
JVM INSTR new #2 <Class Customer$$EnhancerByCGLIB$$9d895b9>;
JVM INSTR dup ;
aclass;
aclass.length;
JVM INSTR tableswitch 0 0: default 35
// 0 28;
goto _L1 _L2
_L2:
JVM INSTR pop ;
Customer$$EnhancerByCGLIB$$9d895b9();
goto _L3
_L1:
JVM INSTR pop ;
throw new IllegalArgumentException("Constructor not found");
_L3:
CGLIB$SET_THREAD_CALLBACKS(null);
return;
}
public Callback getCallback(int i)
{
CGLIB$BIND_CALLBACKS(this);
this;
i;
JVM INSTR tableswitch 0 0: default 30
// 0 24;
goto _L1 _L2
_L2:
CGLIB$CALLBACK_0;
goto _L3
_L1:
JVM INSTR pop ;
null;
_L3:
return;
}
public void setCallback(int i, Callback callback)
{
switch(i)
{
case 0: // '\0'
CGLIB$CALLBACK_0 = (MethodInterceptor)callback;
break;
}
}
public Callback[] getCallbacks()
{
CGLIB$BIND_CALLBACKS(this);
this;
return (new Callback[] {
CGLIB$CALLBACK_0
});
}
public void setCallbacks(Callback acallback[])
{
this;
acallback;
JVM INSTR dup2 ;
0;
JVM INSTR aaload ;
(MethodInterceptor);
CGLIB$CALLBACK_0;
}
private boolean CGLIB$BOUND;
public static Object CGLIB$FACTORY_DATA;
private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
private static final Callback CGLIB$STATIC_CALLBACKS[];
private MethodInterceptor CGLIB$CALLBACK_0;
private static Object CGLIB$CALLBACK_FILTER;
private static final Method CGLIB$findLove$0$Method;
private static final MethodProxy CGLIB$findLove$0$Proxy;
private static final Object CGLIB$emptyArgs[];
private static final Method CGLIB$equals$1$Method;
private static final MethodProxy CGLIB$equals$1$Proxy;
private static final Method CGLIB$toString$2$Method;
private static final MethodProxy CGLIB$toString$2$Proxy;
private static final Method CGLIB$hashCode$3$Method;
private static final MethodProxy CGLIB$hashCode$3$Proxy;
private static final Method CGLIB$clone$4$Method;
private static final MethodProxy CGLIB$clone$4$Proxy;
static
{
CGLIB$STATICHOOK1();
}
public Customer$$EnhancerByCGLIB$$9d895b9()
{
CGLIB$BIND_CALLBACKS(this);
}
}
重写了 Customer 类的所有方法。我们通过代理类的源码可以看到,代理类会获得所有在父类继承来的方法 , 并且会有 MethodProxy与之对应 , 比如MethodCGLIB$findLove 0 0 0Method、MethodProxy CGLIB$findLove 0 0 0Proxy;这些方法在代理类的 findLove()中都有调用。
//代理方法(methodProxy.invokeSuper 会调用)
final void CGLIB$findLove$0()
{
super.findLove();
}
//被代理方法(methodProxy.invoke 会调用, 这就是为什么在拦截器中调用 methodProxy.invoke 会死循环, 一直在调用拦截器)
public final void findLove()
{
CGLIB$CALLBACK_0;
if(CGLIB$CALLBACK_0 != null) goto _L2; else goto _L1
_L1:
JVM INSTR pop ;
CGLIB$BIND_CALLBACKS(this);
CGLIB$CALLBACK_0;
_L2:
JVM INSTR dup ;
JVM INSTR ifnull 37;
goto _L3 _L4
_L3:
break MISSING_BLOCK_LABEL_21;
_L4:
break MISSING_BLOCK_LABEL_37;
this;
CGLIB$findLove$0$Method;
CGLIB$emptyArgs;
CGLIB$findLove$0$Proxy;
//调用拦截器
intercept();
return;
super.findLove();
return;
}
调用过程 : 代理对象调用this.findLove() 方 法 -> 调用拦截器->methodProxy.invokeSuper->CGLIB$findLove$0->被代理对象 findLove()方法。
此时,我们发现拦截器 MethodInterceptor 中就是由 MethodProxy 的 invokeSuper方法调用代理方法的,MethodProxy 非常关键,我们分析一下它具体做了什么。
public class MethodProxy {
private Signature sig1;
private Signature sig2;
private CreateInfo createInfo;
private final Object initLock = new Object();
private volatile FastClassInfo fastClassInfo;
/**
* For internal use by {@link Enhancer} only; see the {@link org.springframework.cglib.reflect.FastMethod} class
* for similar functionality.
*/
public static MethodProxy create(Class c1, Class c2, String desc, String name1, String name2) {
MethodProxy proxy = new MethodProxy();
proxy.sig1 = new Signature(name1, desc);
proxy.sig2 = new Signature(name2, desc);
proxy.createInfo = new CreateInfo(c1, c2);
return proxy;
}
....
}
private static class CreateInfo {
Class c1;
Class c2;
NamingPolicy namingPolicy;
GeneratorStrategy strategy;
boolean attemptLoad;
public CreateInfo(Class c1, Class c2) {
this.c1 = c1;
this.c2 = c2;
AbstractClassGenerator fromEnhancer = AbstractClassGenerator.getCurrent();
if (fromEnhancer != null) {
namingPolicy = fromEnhancer.getNamingPolicy();
strategy = fromEnhancer.getStrategy();
attemptLoad = fromEnhancer.getAttemptLoad();
}
}
}
继续看 invokeSuper()方法:
/**
* Invoke the original (super) method on the specified object.
* @param obj the enhanced object, must be the object passed as the first
* argument to the MethodInterceptor
* @param args the arguments passed to the intercepted method; you may substitute a different
* argument array as long as the types are compatible
* @throws Throwable the bare exceptions thrown by the called method are passed through
* without wrapping in an <code>InvocationTargetException</code>
* @see MethodInterceptor#intercept
*/
public Object invokeSuper(Object obj, Object[] args) throws Throwable {
try {
init();
FastClassInfo fci = fastClassInfo;
return fci.f2.invoke(fci.i2, obj, args);
}
catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
private static class FastClassInfo {
FastClass f1;
FastClass f2;
int i1;
int i2;
}
上面代码调用过程就是获取到代理类对应的 FastClass,并执行了代理方法。之前生成三个 class 文件
Customer$$EnhancerByCGLIB$$9d895b9$$FastClassByCGLIB$$7659219c.class就是代理类的 FastClass,Customer$$FastClassByCGLIB$$6567ea2.class 就是被代理类的 FastClass。
CGLib 动态代理执行代理方法效率之所以比 JDK 的高是因为 Cglib 采用了 FastClass 机制,它的原理简单来说就是:为代理类和被代理类各生成一个 Class,这个 Class 会为代理类或被代理类的方法分配一个 index(int 类型)。这个 index 当做一个入参,FastClass就可以直接定位要调用的方法直接进行调用,这样省去了反射调用,所以调用效率比 JDK动态代理通过反射调用高。下面我们反编译一个 FastClass 看看:
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: <generated>
package com.jarvisy.demo.pattern.proxy.dynamicproxy.cglibproxy;
import java.lang.reflect.InvocationTargetException;
import org.springframework.cglib.core.Signature;
import org.springframework.cglib.proxy.Callback;
import org.springframework.cglib.reflect.FastClass;
public class Customer$$EnhancerByCGLIB$$9d895b9$$FastClassByCGLIB$$7659219c extends FastClass
{
public int getIndex(Signature signature)
{
String s = signature.toString();
s;
s.hashCode();
JVM INSTR lookupswitch 21: default 413
// -1882565338: 188
// -1870561232: 199
// -1745842178: 210
// -1641413109: 221
// -1457535688: 231
// -1411842725: 242
// -1034266769: 253
// -1025895669: 264
// -988317324: 275
// -508378822: 285
// 610042816: 295
// 1096387995: 306
// 1132856532: 317
// 1192015562: 328
// 1246779367: 339
// 1306468936: 350
// 1364367423: 361
// 1800494055: 372
// 1826985398: 383
// 1913648695: 393
// 1984935277: 403;
goto _L1 _L2 _L3 _L4 _L5 _L6 _L7 _L8 _L9 _L10 _L11 _L12 _L13 _L14 _L15 _L16 _L17 _L18 _L19 _L20 _L21 _L22
_L2:
"CGLIB$equals$1(Ljava/lang/Object;)Z";
equals();
JVM INSTR ifeq 414;
goto _L23 _L24
_L24:
break MISSING_BLOCK_LABEL_414;
_L23:
return 16;
_L3:
"CGLIB$findMethodProxy(Lorg/springframework/cglib/core/Signature;)Lorg/springframework/cglib/proxy/MethodProxy;";
equals();
JVM INSTR ifeq 414;
goto _L25 _L26
_L10:
"newInstance([Ljava/lang/Class;[Ljava/lang/Object;[Lorg/springframework/cglib/proxy/Callback;)Ljava/lang/Object;";
equals();
JVM INSTR ifeq 414;
goto _L39 _L40
JVM INSTR pop ;
return -1;
}
//部分代码省略...
public int getIndex(String s, Class aclass[])
{
s;
aclass;
JVM INSTR swap ;
JVM INSTR dup ;
hashCode();
JVM INSTR lookupswitch 19: default 1075
// -1776922004: 168
// -1295482945: 202
// -1053468136: 252
// -679433013: 287
// -331698278: 323
// -124978609: 359
// -60403779: 409
// -29025555: 457
// 85179481: 491
// 94756189: 541
// 147696667: 574
// 161998109: 610
// 495524492: 647
// 1154623345: 697
// 1543336189: 745
// 1811874389: 779
// 1817099975: 927
// 1905679803: 991
// 1951977610: 1041;
goto _L1 _L2 _L3 _L4 _L5 _L6 _L7 _L8 _L9 _L10 _L11 _L12 _L13 _L14 _L15 _L16 _L17 _L18 _L19 _L20
//部分代码省略...
//根据 index 直接定位执行方法
public Object invoke(int i, Object obj, Object aobj[])
throws InvocationTargetException
{
(Customer..EnhancerByCGLIB.._cls9d895b9)obj;
i;
JVM INSTR tableswitch 0 20: default 311
// 0 104
// 1 119
// 2 123
// 3 135
// 4 139
// 5 149
// 6 171
// 7 181
// 8 186
// 9 206
// 10 217
// 11 230
// 12 234
// 13 245
// 14 256
// 15 266
// 16 271
// 17 286
// 18 290
// 19 295
// 20 307;
goto _L1 _L2 _L3 _L4 _L5 _L6 _L7 _L8 _L9 _L10 _L11 _L12 _L13 _L14 _L15 _L16 _L17 _L18 _L19 _L20 _L21 _L22
//部分代码省略...
public int getMaxIndex()
{
return 20;
}
public Customer$$EnhancerByCGLIB$$9d895b9$$FastClassByCGLIB$$7659219c(Class class1)
{
super(class1);
}
}
FastClass 并不是跟代理类一块生成的,而是在第一次执行 MethodProxy invoke/invokeSuper 时生成的并放在了缓存中:
private void init() {
/*
* Using a volatile invariant allows us to initialize the FastClass and
* method index pairs atomically.
*
* Double-checked locking is safe with volatile in Java 5. Before 1.5 this
* code could allow fastClassInfo to be instantiated more than once, which
* appears to be benign.
*/
if (fastClassInfo == null) {
synchronized (initLock) {
if (fastClassInfo == null) {
CreateInfo ci = createInfo;
FastClassInfo fci = new FastClassInfo();
fci.f1 = helper(ci, ci.c1);
fci.f2 = helper(ci, ci.c2);
fci.i1 = fci.f1.getIndex(sig1);
fci.i2 = fci.f2.getIndex(sig2);
fastClassInfo = fci;
createInfo = null;
}
}
}
}
6、 CGLib 和 JDK 动态代理对比
- JDK 动态代理是实现了被代理对象的接口,CGLib 是继承了被代理对象。
- JDK 和 CGLib 都是在运行期生成字节码,JDK 是直接写 Class 字节码,CGLib 使用 ASM框架写 Class 字节码,Cglib 代理实现更复杂,生成代理类比 JDK 效率低。
- JDK 调用代理方法,是通过反射机制调用,CGLib 是通过 FastClass 机制直接调用方法,CGLib 执行效率更高。
- JDK是采用读取接口的信息,CGLib覆盖父类方法。目的:都是生成一个新的类,去实现增强代码逻辑的功能。
- JDK Proxy 对于用户而言,必须要有一个接口实现,目标类相对来说复杂,CGLib 可以代理任意一个普通的类,没有任何要求。
- CGLib 生成代理逻辑更复杂,效率,调用效率更高,生成一个包含了所有的逻辑的FastClass,不再需要反射调用JDK Proxy生成代理的逻辑简单,执行效率相对要低,每次都要反射动态调用。
- CGLib 有个坑,CGLib不能代理final的方法。
7、代理模式与Spring
代理模式在 Spring 源码中的应用
先看 ProxyFactoryBean 核心的方法就是 getObject()方法,我们来看一下源码:
/**
* Return a proxy. Invoked when clients obtain beans from this factory bean.
* Create an instance of the AOP proxy to be returned by this factory.
* The instance will be cached for a singleton, and create on each call to
* {@code getObject()} for a proxy.
* @return a fresh AOP proxy reflecting the current state of this factory
*/
@Override
@Nullable
public Object getObject() throws BeansException {
initializeAdvisorChain();
if (isSingleton()) {
return getSingletonInstance();
}
else {
if (this.targetName == null) {
logger.info("Using non-singleton proxies with singleton targets is often undesirable. " +
"Enable prototype proxies by setting the 'targetName' property.");
}
return newPrototypeInstance();
}
}
在getObject()方法中,主要调用 getSingletonInstance()和 newPrototypeInstance();在 Spring 的配置中,如果不做任何设置,那么 Spring 代理生成的 Bean 都是单例对象。如果修改 scope 则每次创建一个新的原型对象。
newPrototypeInstance()里面的逻辑比较复杂,这里不做了解。
Spring 利用动态代理实现 AOP 有两个非常重要的类,一个是 JdkDynamicAopProxy 类和 CglibAopProxy 类,来看一下类图:
Spring 中的代理选择原则
- 当 Bean 有实现接口时,Spring 就会用 JDK 的动态代理。
- 当 Bean 没有实现接口时,Spring 选择 CGLib。
- Spring 可以通过配置强制使用 CGLib,只需在 Spring 的配置文件中加入如下代码:
<aop:aspectj-autoproxy proxy-target-class="true"/>