SSM学习笔记(5)-CGLIB动态代理

问题:

1、CGLIB动态代理与JDK的对比

2、实现

解决:

1、CGLIB是适用于不需要接口的情况下,只需要个非抽象的类就可以实现动态代理。

2、CGLIB动态代理

 1 public class CglibProxyExample implements MethodInterceptor{
 2     /**
 3     *生成CGLIB代理对象
 4     **/
 5     public Object getProxy(Class cls){
 6         //CGLIB enhancer 增强类对象
 7         Enhancer enhancer = new Enhancer();
 8         //设置增强类型
 9         enhancer.setSuperclass(cls);
10         //定义代理逻辑对象为当前对象,要求当前对象实现MethodInterceptor方法
11         enhancer.setCallback(this);//
12         //生成并返回代理对象
13         return enhancer.create();
14     }
15     
16     /**代理逻辑方法
17     *
18     */
19     //intercept(拦截)
20     public Object intercept(Object proxy, Method method,
21     Object[] args, MethodProxy methodProxy) throws Throwable{
22     System.err.println("调用真实对象前");
23     //CGLIB反射调用真实对象方法
24     Object result = methodProxy.invokeSuper(proxy, args);
25     System.err.println("调用真实对象后");
26     return result;
27     }
28 }
View Code

测试CGLIB动态代理

1 public void textCGLIBProxy(){
2     CglibProxyExample cpe = new CglibProxyExample();
3     ReflectServiceImpl obj = (ReflectServiceImpl)cpe.getProxy(ReflectServiceImpl.class);
4     obj.sayHello("张三");
5 }
View Code

猜你喜欢

转载自www.cnblogs.com/quenvpengyou/p/12811469.html