zoukankan      html  css  js  c++  java
  • CGLIB动态代理模式

    • 概念:第三方技术CGLIB动态代理和JDK代理不同的是,JDK代理需要提供接口,而CGLIB代理不需要。它只需要一个非抽象类就能实现动态代理
    • 例子:
     1 /**
     2  * 非抽象类
     3  * @author Administrator
     4  *
     5  */
     6 public class HelloService {
     7 
     8     void say(){
     9         System.out.println("看见");
    10     }
    11 }
    非抽象类
    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 CglibProxyExample implements MethodInterceptor{
    
        
        /**
         * 生成CGLIB代理对象
         * @param cls    Class类
         * @return        Class类的CGLIB代理对象
         */
        @SuppressWarnings("rawtypes")
        public Object getInstance(Class cls) {  
            //CGLIB  enhancer增强类对象  
            Enhancer enhancer = new Enhancer(); 
            //设置增强类型
            enhancer.setSuperclass(cls);  
            //定义代理逻辑对象为当前对象,要求当前对象实现MethodInterceptor方法
            enhancer.setCallback(this);  
            //生成并返回代理对象  
            return enhancer.create();  
        }  
        
        
        @Override
        public Object intercept(Object arg0, Method arg1, 
                Object[] arg2, MethodProxy arg3) throws Throwable {
            // TODO Auto-generated method stub
            System.out.println("事务开始");
            //CGLIB反射调用真实对象的方法
            Object invoke=arg3.invokeSuper(arg0, arg2);  
            System.out.println("事务结束");  
            return invoke;  
        }
    
    }
     1 /**
     2  * cglib动态代理
     3  * @author 开发
     4  *
     5  */
     6 public class TestCglib {
     7     
     8     public static void main(String args[]){  
     9         CglibProxyExample s=new CglibProxyExample();      
    10         HelloService s1=(HelloService)s.getInstance(HelloService.class);  
    11         s1.say(); 
    12     }    
    13 }
    调用Demo
    • 解析:使用了CGLIB的加强者Enhancer后,设置超类方法(setSuperclass),通过(setCallback)方法设置哪个类为代理类,this表示当前类。那么当前类就得实现接口MethodInterceptor的方法intercept,然后返回代理对象。代理的逻辑可以在方法intercept中实现,通过该方法从而达到控制真实对象的目的。
  • 相关阅读:
    tomcat+nginx+redis实现均衡负载、session共享
    基于Java的开源3D游戏引擎jMonkeyEngine
    父线程,没有等子线程执行完就退出
    sun.misc.BASE64Encoder找不到jar包的解决方法
    perl (Ss+)+
    安装,配置kafka
    Uncaught Error: Error calling method on NPObject.
    Caused by: org.apache.ibatis.ognl.OgnlException: source is null for getProperty(null, "list")
    error='Cannot allocate memory'
    大众点评CAT安装部署记录
  • 原文地址:https://www.cnblogs.com/LJing21/p/10705004.html
Copyright © 2011-2022 走看看