一.简介
- 不需要目标类接口就可以产生代理对象
- cglib的Enhancer类和MethodInterceptor接口来实现创建代理类
二.代码
1.目标类
package com.jp.cglibproxy;
import com.jp.domain.User;
public class UserDaoImpl {
public void save(User user) {
System.out.println("保存用户成功");
}
}
2.拦截器
package com.jp.cglibproxy;
import java.lang.reflect.Method;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import com.jp.transcation.Logger;
import com.jp.transcation.MyTranscation;
public class MyInterceptor implements MethodInterceptor {
private Object target;
private Logger log;
private MyTranscation myTranscation;
public MyInterceptor(Object target, Logger log, MyTranscation myTranscation) {
super();
this.target = target;
this.log = log;
this.myTranscation = myTranscation;
}
public Object createProxy(){
Enhancer enhancer=new Enhancer();
enhancer.setCallback(this);
enhancer.setSuperclass(this.target.getClass());
return enhancer.create();
}
@Override
public Object intercept(Object arg0, Method arg1, Object[] arg2,MethodProxy arg3) throws Throwable {
myTranscation.begin();
log.log();
arg1.invoke(this.target, arg2);
myTranscation.commit();
return null;
}
}
3.测试类
package com.jp.cglibproxy;
import com.jp.domain.User;
import com.jp.transcation.Logger;
import com.jp.transcation.MyTranscation;
public class CglibProxyTest {
public static void main(String[] args) {
UserDaoImpl u=new UserDaoImpl();
Logger log=new Logger();
MyTranscation mt=new MyTranscation();
MyInterceptor m=new MyInterceptor(u,log,mt);
UserDaoImpl createProxy = (UserDaoImpl)m.createProxy();
User user=new User();
createProxy.save(user);
}
}
三.jdk和cglib包动态代理区别
- 目标类实现接口
利用jdk产生代理对象,代理对象是接口的一个子类
代理对象和目标类是平级关系 - 目标类没有实现接口
利用cglib包产生代理对象,代理对象是目标类的一个子类
代理对象和目标类是子父类关系
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8fb215cc7e95e377cf163affac67a338.png)