CGLIB介绍
https://github.com/cglib/cglib
About
cglib - Byte Code Generation Library is high level API to generate and transform Java byte code. It is used by AOP, testing, data access frameworks to generate dynamic proxy objects and intercept field access.
JDK动态代理,必须对 interface 进行代理;而,CGLIB 能直接对 类 进行代理。
要设置 pom 文件
https://mvnrepository.com/artifact/cglib/cglib/3.3.0
<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
直接见代码
类 — 代理商
/**
* 动态代理 - CGLIB : 代理商网点
* @version 0.1
* @author BaiJing.biz
*/
public class AgentOutlets {
public void sell() {
System.out.println("Agent 代理商销售商品");
}
}
工厂类
/**
* 动态代理 - CGLIB : 代理商网点
* @version 0.1
* @author BaiJing.biz
*/
public class ProxyFactory implements MethodInterceptor {
private AgentOutlets agentOutlets = new AgentOutlets();
public AgentOutlets getProxyObject() {
// 创建 Enhancer 对象
Enhancer enhancer = new Enhancer();
// 父类的字节码对象
enhancer.setSuperclass(AgentOutlets.class);
// 设置回调函数 , this 子实现类对象
enhancer.setCallback(this);
// 创建代理对象
AgentOutlets proxyObjcet = (AgentOutlets) enhancer.create();
return proxyObjcet;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("inetercept 执行中 ... ");
System.out.println("CGLIB 代理,销售点收取服务费用 ...");
// 调用目标对象的方法
Object object = method.invoke(agentOutlets, objects);
return object;
}
}
继承 implements MethodInterceptor 实现具体的代理点销售行为。
客户
public class CustomerRun {
public static void main(String[] args) {
// 代理工厂对象
ProxyFactory factory = new ProxyFactory();
// 获取代理对象
Trade proxyObject = factory.getProxyObject();
// Sell ,调用代理对象的方法
proxyObject.sell();
}
}
结果
静态代理参考:
设计模式(Design pattern)代理模式(Proxy Pattern)之静态代理(Static Proxy)-CSDN博客
JDK 动态代理参考
设计模式(Design pattern)代理模式(Proxy Pattern)之动态代理(Dynamic Pattern)-CSDN博客