CGLIB动态代理模式

概念:第三方技术CGLIB动态代理和JDK代理不同的是,JDK代理需要提供接口,而CGLIB代理不需要。它只需要一个非抽象类就能实现动态代理

/**
  * 非抽象类
  * @author Administrator
  */
public class HelloService {
     void say(){
         System.out.println("看见");
     }
}
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;  
    }
}
/**
  * cglib动态代理
  * @author 开发
  */
public class TestCglib {    
    public static void main(String args[]){  
         CglibProxyExample s=new CglibProxyExample();      
         HelloService s1=(HelloService)s.getInstance(HelloService.class);  
         s1.say(); 
    }    
}

解析:使用了CGLIB的加强者Enhancer后,设置超类方法(setSuperclass),通过(setCallback)方法设置哪个类为代理类,this表示当前类。

那么当前类就得实现接口MethodInterceptor的方法intercept,然后返回代理对象。代理的逻辑可以在方法intercept中实现,通过该方法从而达到控制真实对象的目的。

 

posted @ 2019-04-16 11:11  21karat  阅读(184)  评论(0编辑  收藏  举报