代码
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的应用?