【Java】CGLIB动态代理

一. CGLIB动态代理示例

1. 被代理对象

public class UserServiceImpl {

    public void addUser(String name) {
        System.out.println("add user into database.");
    }
    
    public String getUser(String name) {
        
        System.out.println("getUser from database.");
        return name;
    }
}


2. 代理工具类

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 CGProxy implements MethodInterceptor{

    private Object target;    // 被代理对象
    
    public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy proxy) throws Throwable {
    
        System.out.println("do sth before....");
        
        Object result = proxy.invokeSuper(arg0, arg2);
        
        System.out.println("do sth after....");
        
        return result;
    }
    
    public Object getProxyObject(Object target) {
    
        this.target = target;
     
        Enhancer enhancer = new Enhancer();
        
        // 设置父类
        enhancer.setSuperclass(this.target.getClass());
        
        // 设置回调(在调用父类方法时,回调 this.intercept())
        enhancer.setCallback(this);
        
        // 创建代理对象
        return enhancer.create();
    }
}


3. 使用代理类

public class CGProxyTest {

    public static void main(String[] args){
    
        UserServiceImpl userServiceImpl = new UserServiceImpl();    // 被代理的对象

        // 创建代理对象(创建的代理对象可以放在容器中缓存,后续调用时获取即可)
        UserServiceImpl proxyObject = (UserServiceImpl) new CGProxy().getProxyObject(userServiceImpl);
        
        proxyObject.getUser("1");
        proxyObject.addUser("1");
    }
}


5. 执行结果


do sth before....
getUser from database.
do sth after....

do sth before....
add user into database.
do sth after....


二. CGLIB动态代理说明

1. 获取代理对象:CGProxy.getProxyObject

2. 调用代理方法:CGProxy.intercept

3. 原理

  1. CGLIB是基于继承机制,继承被代理类,所以方法不要声明为final,通过重写父类方法达到增强类的作用
  2. 底层是基于asm第三方框架,把代理对象类的class文件加载进来,通过修改其字节码生成新的子类来处理
  3. 生成类的速度慢,但是后续执行类的操作时很快

4. 参考资料

https://www.jianshu.com/p/9a61af393e41?from=timeline&isappinstalled=0

posted @ 2021-03-17 12:16    阅读(352)  评论(0编辑  收藏  举报