Spring如何基于Proxy及cglib实现动态代理
spring中提供了两种动态代理的方式,分别是JavaProxy以及cglib
JavaProxy只能代理接口,而cglib是通过继承的方式,实现对类的代理
添加一个接口以及对应的实现类
publicinterfaceHelloInterface{
voidsayHello();
}
publicclassHelloInterfaceImplimplementsHelloInterface{
@Override
publicvoidsayHello(){
System.out.println("hello");
}
}
JavaProxy通过实现InvocationHandler实现代理
publicclassCustomInvocationHandlerimplementsInvocationHandler{
privateHelloInterfacehelloInterface;
publicCustomInvocationHandler(HelloInterfacehelloInterface){
this.helloInterface=helloInterface;
}
@Override
publicObjectinvoke(Objectproxy,Methodmethod,Object[]args)throwsThrowable{
System.out.println("beforehelloforproxy");
Objectresult=method.invoke(helloInterface,args);
System.out.println("afterhelloforproxy");
returnresult;
}
}
而cglib实现MethodInterceptor进行方法上的代理
publicclassCustomMethodInterceptorimplementsMethodInterceptor{
@Override
publicObjectintercept(Objecto,Methodmethod,Object[]objects,MethodProxymethodProxy)throwsThrowable{
System.out.println("beforehelloforcglib");
Objectresult=methodProxy.invokeSuper(o,objects);
System.out.println("afterhelloforcglib");
returnresult;
}
}
分别实现调用代码
publicstaticvoidmain(String[]args){
Enhancerenhancer=newEnhancer();
enhancer.setSuperclass(HelloInterfaceImpl.class);
enhancer.setCallback(newCustomMethodInterceptor());
HelloInterfacetarget=(HelloInterface)enhancer.create();
target.sayHello();
CustomInvocationHandlerinvocationHandler=newCustomInvocationHandler(newHelloInterfaceImpl());
HelloInterfacetarget2=(HelloInterface)Proxy.newProxyInstance(Demo.class.getClassLoader(),newClass[]{HelloInterface.class},invocationHandler);
target2.sayHello();
}
可以看到对于的代理信息输出
beforehelloforcglib hello afterhelloforcglib beforehelloforproxy hello afterhelloforproxy
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。