JDK实现动态代理需要实现类通过接口定义业务方法,对于没有接口的类,如何实现动态代理呢,这就需要CGLib了。CGLib采用了非常底层的字节码技术,其原理是通过字节码技术为一个类创建子类,并在子类中采用方法拦截的技术拦截所有父类方法的调用,顺势织入横切逻辑,所以用final修饰的方法将不能实现代理。同样我们采用jdk动态案例分析说明
1、创建实体类
- package www.csdn.spring.cglib.proxy;
- //真实主题角色
- public class SayGoodByeImpl {
- public void say(String content) {
- System.out.println("say:" + content);
- }
- }
2、测试说明:
- package www.csdn.spring.cglib.proxy;
- import org.junit.Test;
- public class TestSay {
- @Test
- public void say(){
- //真实主题角色
- SayGoodByeImpl sayGoodByeImpl = new SayGoodByeImpl();
- //自己和女朋友说
- sayGoodByeImpl.say("咱们分手吧!");
- }
- }
3、采用cglib代理实现
- package www.csdn.spring.cglib.proxy;
- 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 CglibProxy implements MethodInterceptor {
- // 目标对象
- private Object target;
- // 创建代理对象
- public Object createProxyInstance(Object target) {
- this.target = target;
- Enhancer enhancer = new Enhancer(); // 用于生成代理对象的
- enhancer.setSuperclass(this.target.getClass());// 用于设置代理对象的父类
- enhancer.setCallback(this); // 设置回调
- return enhancer.create(); // 创建代理对象
- };
- /**
- * proxy:目标对象代理的实例 method:目标对象调用父类方法的method实例 args:调用父类方法传递参数
- * methodProxy:代理的方法去调用目标方法
- */
- @Override
- public Object intercept(Object proxy, Method method, Object[] args,
- MethodProxy methodProxy) throws Throwable {
- Object returnValue = null;
- // 目标方法执行之前的操作
- beforeMethod();
- // 执行目标方法
- returnValue = methodProxy.invoke(target, args);
- // 目标方法执行之后的操作
- afterMethod();
- return returnValue;
- }
- public void beforeMethod() {
- System.out.println("---------------------目标方法之前执行");
- }
- public void afterMethod() {
- System.out.println("---------------------目标方法之后执行");
- }
- }
4、测试说明:
- package www.csdn.spring.cglib.proxy;
- import org.junit.Test;
- public class TestSay {
- @Test
- public void say(){
- //真实主题角色
- SayGoodByeImpl sayGoodByeImpl = new SayGoodByeImpl();
- //代理角色
- CglibProxy cglibProxy = new CglibProxy();
- //创建了一个 目标类的子类的对象
- SayGoodByeImpl proxy = (SayGoodByeImpl) cglibProxy.createProxyInstance(sayGoodByeImpl);
- //代理说
- proxy.say("你和他分手吧!");
- }
- }