CGLib动态代理
来源:互联网 发布:死是什么感觉 知乎 编辑:程序博客网 时间:2024/06/15 16:52
代码
package com.itheima.spring.cglibproxy;
public class PersonDaoImpl{
public void savePerson() {
System.out.println("save person");
}
}
package com.itheima.spring.cglibproxy;
public class Transaction {
public void beginTransaction(){
System.out.println("begin transcation");
}
public void commit() {
System.out.println("commit");
}
}
package com.itheima.spring.cglibproxy;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class MyInterceptor implements MethodInterceptor{
private Transaction transaction;
private Object target;
public MyInterceptor(Object target, Transaction transaction ) {
super();
this.transaction = transaction;
this.target = target;
}
public Object createProxy(){
//代码增强类
Enhancer enhancer = new Enhancer();
enhancer.setCallback(this);//参数为拦截器
enhancer.setSuperclass(target.getClass());//生成的代理类的父类是目标类
return enhancer.create();
}
@Override
public Object intercept(Object object, Method method, Object[] arg2,
MethodProxy arg3) throws Throwable {
this.transaction.beginTransaction();
method.invoke(target);
this.transaction.commit();
return null;
}
}
package com.itheima.spring.cglibproxy;
import org.junit.Test;
/**
* 通过cglib产生的是代理对象,代理类是目标类的子类
* @author xx
*
*/
public class CGLibProxyTest {
@Test
public void testCGlib(){
Object target = new PersonDaoImpl();
Transaction transaction = new Transaction();
MyInterceptor interceptor = new MyInterceptor(target,transaction);
PersonDaoImpl personDaoImpl = (PersonDaoImpl)interceptor.createProxy();
personDaoImpl.savePerson();
}
}
思考
1、JDK动态代理与CGLib动态代理的比较?
2、在Spring中何时用到JDK或者CGLib实现的AOP?
3、如何通过调试查看当前用到的是JDK还是CGLib?
CGLib的标志:
JDK的标志:
4、如何强制用CGLib实现AOP?
5、cglib的应用?
0 0
- 动态代理-CGLib动态代理
- 初识CGLIB动态代理
- Cglib 动态代理
- CGLib 动态代理
- 动态代理-->cglib
- cglib动态代理介绍
- cglib动态代理
- CGLIB 动态代理。
- CGLIB动态代理
- CGLIB实现动态代理
- cglib 动态代理
- cglib动态代理模式
- cglib动态代理
- cglib动态代理
- CGLIB 动态代理
- cglib动态代理
- 动态代理CGLIB
- CGLIB动态代理应用
- 学习图谱
- JDK动态代理
- BitMap的getRowBytes和getByteCount()
- Shaders for Game Programmers and Artists(7) - Non-photorealistic rendering
- [07]项目实战-PC 端固定布局(7)
- CGLib动态代理
- Synchronized(对象锁)和Static Synchronized(类锁)的区别
- 1720 (错误)
- codeforce 698B Fix a Tree
- TCP建立连接为什么是三次握手,为什么不是两次或四次?
- SWIFT 函数参数 3.0 改动--Boolan
- C语言中realloc,malloc,calloc区别
- SystemBarTint实现沉浸模式
- Shaders for Game Programmers and Artists(8) - Fog