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

    JDK动态代理必须要提供接口才能使用,有些不能提供结果的环境只能采用第三方技术,如CGLIB,优势在于不需要提供接口,只要一个非抽象类就可以实现动态代理

    1.非抽象类:

    public class HelloWorldImpl 
    {
    
        public void sayHelloWorld() 
        {
            System.out.println("hello world.....");
        }
    
        public void sayBye() 
        {
            System.out.println("good bye.....");
        }
    
    }

    2. 实现动态代理

    public class CglibProxy implements MethodInterceptor
    {
        public Object getProxy(Class cls)
        {
            //增强类对象
            Enhancer enhancer = new Enhancer();
            //设置增强类
            enhancer.setSuperclass(cls);
            //定义代理对象为当前对象, 要求当前对象实现 MethodInterceptor方法
            enhancer.setCallback(this);
            //返回并生成代理对象
            return enhancer.create();
        }
    
        @Override
        public Object intercept(Object proxy, Method method, Object[] args, MethodProxy proxyMethod) throws Throwable {
            System.out.println("调用真实方法前");
            //Cg 反射调用真实对象方法
            Object obj = proxyMethod.invokeSuper(proxy, args);
            System.out.println("调用真实方法后");
            return obj;
        }
    
    }

    3.测试:

    public class CGTest {
    
        public static void main(String[] args) 
        {
            CglibProxy proxy = new CglibProxy();
            HelloWorldImpl obj = (HelloWorldImpl) proxy.getProxy(HelloWorldImpl.class);
            obj.sayHelloWorld();
            obj.sayBye();
        }
    }
    输出:
    调用真实方法前
    hello world.....
    调用真实方法后
    调用真实方法前
    good bye.....
    调用真实方法后

    JDK和CGLIB都是生成代理对象,制定代理逻辑类,而代理逻辑类只需要实现一个接口的一个方法,这个方法是代理对象的逻辑方法,他可以控制真实对象的方法。

  • 相关阅读:
    Unique Binary Search Trees——LeetCode
    Binary Tree Inorder Traversal ——LeetCode
    Maximum Product Subarray——LeetCode
    Remove Linked List Elements——LeetCode
    Maximum Subarray——LeetCode
    Validate Binary Search Tree——LeetCode
    Swap Nodes in Pairs——LeetCode
    Find Minimum in Rotated Sorted Array——LeetCode
    Linked List Cycle——LeetCode
    VR AR MR
  • 原文地址:https://www.cnblogs.com/daxiong225/p/9900503.html
Copyright © 2011-2022 走看看