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中实现,通过该方法从而达到控制真实对象的目的。
  • 相关阅读:
    说说内核与计算机硬件结构
    为什么51单片机的地址总线是16位的,但是它却是8位机?
    哈弗结构与冯诺依曼结构
    关于ARM的内核架构
    Bootloader之uBoot简介(转)
    mysql优化
    java上传并下载以及解压zip文件有时会报文件被损坏错误分析以及解决
    [Java]读取文件方法大全
    request相关研究
    session与cookie
  • 原文地址:https://www.cnblogs.com/LJing21/p/10705004.html
Copyright © 2011-2022 走看看