03、Spring中的静态代理JDK动态代理CGLB动态代理
创始人
2024-02-14 23:04:40
0

本文章主要讲解以下几个点:
1、代理模式
2、静态代理
3、JDK的动态代理
4、CGLB动态代理

1、代理模式

1、定义

给某一个对象提供一个代理,并由代理对象控制对原对象的引用。

2、通俗解释

比如:一个人(客户端)需要去租房子,但是找不到房子,就会去找中介(代理对象)租房子,真实的房子主人(真实对象)并不会被客户端知晓。所有的租房子操作都是由中介代理办理。

3、好处

  • 代理模式能够协调调用者和被调用者,在一定程度上降低代码之间的耦合度。
  • 实现了职责分离

2、静态代理

1、定义

在程序运行之前就已经存在代理类的字节码文件,代理对象和真实对象的关系在程序运行之前就确定了。(代理对象需要我们自己去手动创建)

2、类图

在这里插入图片描述

3、 代码演示

1、 新建一个Maven项目导入如下依赖

org.springframeworkspring-context5.0.8.RELEASEorg.springframeworkspring-test5.0.8.RELEASEtestjunitjunit4.12test

2、提供一个接口

package cn.simplelife._01staticProxy;/*** @ClassName IEmployeeService* @Description* @Author simplelife* @Date 2022/11/22 19:14* @Version 1.0*/public interface IEmployeeService {void save(String name, String password);
}

3、创建实现类实现接口

package cn.simplelife._01staticProxy.impl;import cn.simplelife._01staticProxy.IEmployeeService;/*** @ClassName IEmployeeServiceImpl* @Description* @Author simplelife* @Date 2022/11/22 19:15* @Version 1.0*/public class IEmployeeServiceImpl implements IEmployeeService {@Overridepublic void save(String name, String password) {System.out.println("保存" + name);}
}

4、创建代理类实现接口

package cn.simplelife._01staticProxy.proxy;import cn.simplelife._01staticProxy.IEmployeeService;
import cn.simplelife._01staticProxy.tx.MyTransaction;
import org.springframework.stereotype.Component;/*** @ClassName IEmployeeProxy* @Description* @Author simplelife* @Date 2022/11/22 19:24* @Version 1.0*/
@Component
public class IEmployeeProxy implements IEmployeeService {private MyTransaction myTransaction; // 事务管理对象private IEmployeeService target; // 代理类中的真实类对象// 因为使用的是XML配置方式,所以这里必须提供Set方法public void setMyTransaction(MyTransaction myTransaction) {this.myTransaction = myTransaction;}public void setTarget(IEmployeeService target) {this.target = target;}@Overridepublic void save(String name, String password) {try {myTransaction.begin();// 真实类对象调用真实类的方法保存信息target.save(name, password);myTransaction.commit();} catch (Exception e) {myTransaction.rollback();e.printStackTrace();}}
}

5、使用Spring帮我们创建对象




6、编写测试类进行测试

package cn.simplelife._01staticProxy.proxy;import cn.simplelife._01staticProxy.IEmployeeService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/*** @ClassName IEmployeeProxyTest* @Description* @Author simplelife* @Date 2022/11/22 19:29* @Version 1.0*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class IEmployeeProxyTest {@Autowiredprivate IEmployeeService iEmployeeService;@Testpublic void save() {System.out.println(iEmployeeService);iEmployeeService.save("张胜男","12315");}
}

7、测试结果

在这里插入图片描述

3、JDK动态代理

1、相关API简介

1、java.lang.reflect.Proxy

  • Java 动态代理机制生成的所有动态代理类的父类,它提供了一组静态方法来为一组接口动态地生成代理类及其对象。

  • 主要方法

public static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler hanlder)
  • 方法职责:为指定类加载器、一组接口及调用处理器生成动态代理类实例。

  • 参数:

    • loader:类加载器,一般传递真实对象的类加载器
    • interfaces:代理类所需要实现的接口
    • hanlder:代理执行处理器,代理对象需要做的事情。
  • 返回值:创建的代理对象。

2、java.lang.reflect.InvocationHandler

  • 主要方法
public Object invoke(Object proxy, Method method, Object[] args)
  • 方法职责:负责集中处理动态代理类上的所有方法调用,让使用者自定义做什么事情,对原来方法增强。

  • 参数:

    • proxy :生成的代理对象;
    • method:当前调用的真实方法对象;
    • args :当前调用方法的实参。
  • 返回值:真实方法的返回结果。

2、优缺点

1、优点

  • 对比静态代理,我们不需要手动创建代理类。

2、缺点

  • 真实类必须实现接口。
  • 对多个真实对象进行代理的话,若使用 Spring 的话配置太多了,要手动创建代理对象,用起来麻烦。

3、代码演示

1、 新建一个Maven项目导入如下依赖

org.springframeworkspring-context5.0.8.RELEASEorg.springframeworkspring-test5.0.8.RELEASEtestjunitjunit4.12test

2、提供一个接口

package cn.simplelife._01staticProxy;/*** @ClassName IEmployeeService* @Description* @Author simplelife* @Date 2022/11/22 19:14* @Version 1.0*/public interface IEmployeeService {void save(String name, String password);
}

3、创建实现类实现接口

package cn.simplelife._01staticProxy.impl;import cn.simplelife._01staticProxy.IEmployeeService;/*** @ClassName IEmployeeServiceImpl* @Description* @Author simplelife* @Date 2022/11/22 19:15* @Version 1.0*/public class IEmployeeServiceImpl implements IEmployeeService {@Overridepublic void save(String name, String password) {System.out.println("保存" + name);}
}

4、编写代理执行处理器类

package cn.simplelife.jdkproxy.handler;import cn.simplelife.jdkproxy.tx.MyTransactionManger;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;/*** @ClassName IEmployeeServiceProxy* @Description* @Author simplelife* @Date 2022/11/22 19:55* @Version 1.0*/public class TransactionInvocationHandler implements InvocationHandler {private MyTransactionManger myTransactionManger; // 事务管理器private Object target; // 真实对象public void setMyTransactionManger(MyTransactionManger myTransactionManger) {this.myTransactionManger = myTransactionManger;}public void setTarget(Object target) {this.target = target;}public Object getTarget() {return target;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object invoke = null;try {myTransactionManger.begin();// 真实对象调用方法invoke = method.invoke(target, args);myTransactionManger.commit();} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {myTransactionManger.rock();e.printStackTrace();}return invoke;}
}

5、使用Spring帮我们创建对象




6、编写测试类进行测试

package cn.simplelife.jdkproxy.handler;import cn.simplelife.jdkproxy.IEmployeeService;
import cn.simplelife.jdkproxy.impl.IEmployeeServiceImpl;
import cn.simplelife.jdkproxy.tx.MyTransactionManger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.lang.reflect.Proxy;/*** @ClassName IEmployeeServiceProxyTest* @Description* @Author simplelife* @Date 2022/11/22 19:58* @Version 1.0*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class IEmployeeServiceProxyTest {@Autowiredprivate TransactionInvocationHandler invocationHandler;@Testpublic void testJDKProxy() {invocationHandler.setMyTransactionManger(new MyTransactionManger());invocationHandler.setTarget(new IEmployeeServiceImpl());IEmployeeService proxyInstance = (IEmployeeService) Proxy.newProxyInstance(this.getClass().getClassLoader(),invocationHandler.getTarget().getClass().getInterfaces(),invocationHandler);proxyInstance.save("李四", "11345");}
}

7、测试结果

在这里插入图片描述

8、底层分析图解

在这里插入图片描述

9、调用流程

在这里插入图片描述

4、CGLB动态代理

1、相关API简介

1、org.springframework.cglib.proxy.Enhancer

类似 JDK 中 Proxy,用来生成代理类创建代理对象的。

2、org.springframework.cglib.proxy.InvocationHandler

类似 JDK 中 InvocationHandler,让使用者自定义做什么事情,对原来方法增强。

2、代码演示

1、修改代理执行处理器类

  • 修改其实现接口为 org.springframework.cglib.proxy.InvocationHandler,其他不变。

2、修改单元测试类

package cn.simplelife.cjlbproxy.impl;import cn.simplelife.cjlbproxy.IEmployeeService;
import cn.simplelife.cjlbproxy.handler.TransactionInvokeHandler;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/*** @ClassName IEmployeeServiceImplTest* @Description* @Author simplelife* @Date 2022/11/22 15:38* @Version 1.0*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class IEmployeeServiceImplTest {@Autowiredprivate TransactionInvokeHandler transactionInvokeHandler;@Testpublic void save() {Enhancer enhancer = new Enhancer();// 生产的代理类是继承真实类的enhancer.setSuperclass(transactionInvokeHandler.getTarget().getClass());// 生成的代理类对象要做的事情enhancer.setCallback(transactionInvokeHandler);// 接收生成的代理类IEmployeeService iEmployeeService = (IEmployeeService) enhancer.create();iEmployeeService.save("yyy", "123");}
}

3、测试结果

在这里插入图片描述

4、调用流程

在这里插入图片描述

相关内容

热门资讯

66名中俄律师入选东北亚涉外律... 中新社哈尔滨8月23日电 (记者 史轶夫)中国·哈尔滨-俄罗斯·滨海边疆区涉外法律服务交流会23日在...
原创 于... 最近男星许凯陷入出轨劈腿私生活混乱的风波当中,虽然于正和许凯本人对此事已经发声明澄清辟谣,但随着此事...
山西网警“净网”行动集中收网,... 来源:极目新闻 为深入推进“净网-2025”专项工作,持续加大对网络违法犯罪的打击力度,近日,在山西...
原创 特... 特朗普终于在纽约法庭赢了一局。8月21日,当地上诉法院撤销了对他和特朗普集团近5亿美元的民事欺诈罚款...
女子在景区台阶上滑倒致老人摔伤... 近日,一女子发帖反映称自己在云南丽江一景区滑倒,同时撞到前方一名老人,导致对方受伤。 8月21日,九...
法律诉讼委托公证全解析:材料、... 1. 打官司为啥要办公证?很多人不知道的坑 打官司前办公证这事儿,好多人都觉得麻烦不想弄。但你知道...
国子软件中标:巴音郭楞蒙古自治... 证券之星消息,根据天眼查APP-财产线索数据整理,根据巴音郭楞蒙古自治州公安局食品药品环境犯罪侦查分...
巴西总统:某些国家以打击犯罪为... 当地时间22日,正在哥伦比亚参加《亚马孙合作条约》成员总统会议的巴西总统卢拉表示,某些富裕国家以“打...
贵州省法律援助中心开展系列法律... 为不断扩大《中华人民共和国法律援助法》《贵州省法律援助条例》的关注度和知晓率,努力提高法律援助工作的...
原创 马... 据报道,加勒比海风起云涌。路透社放出独家消息:未来36小时内,三艘美国宙斯盾驱逐舰将带着数千兵力压向...