cglib動態代理舉例

jdk的動態代理是基於接口的代理,而cglib不要求實現接口,是一種基於繼承的代理,使用字節碼生成被代理類的子類node

 

public class TestMethodInterceptor implements MethodInterceptor {

    private Object targetObject;

    public TestMethodInterceptor(Object target){
        this.targetObject = target;
    }

    public Object getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetObject.getClass());
        enhancer.setCallback(this);
        Object proxy = enhancer.create();
        return proxy;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("intercept begin");
        System.out.println("class:" + o.getClass().getName() + ", method:"+ method.getName());
        System.out.println("class:" + methodProxy.getClass().getName() + ", method:"+ method.getName());
        methodProxy.invokeSuper(o,objects);
        method.invoke(targetObject,objects);
        System.out.println("intercept end");
        return null;
    }

}
    public static void main(String[] args) {
        SayImpl sayProxy = (SayImpl)new TestMethodInterceptor(new SayImpl()).getProxyInstance();
        sayProxy.sayHello("my dear");
    }

 

執行結果:spring

intercept begin
class:com.cainiao.wmpinbound.refund.job.register.node.SayImpl$$EnhancerByCGLIB$$1e0a054, method:sayHello
class:org.springframework.cglib.proxy.MethodProxy, method:sayHello
hello:my dear
hello:my dear
intercept endide

相關文章
相關標籤/搜索