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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下