初见cglib

今天在看spring文档的时候看到了cglib代理. 出于好奇,就去搜索了一下.
深入理解CGLIB动态代理机制
并没有很深入的去了解这个代理机制,只是简单的看了一下怎么用. 毕竟现在主要还是学习spring文档.

之前也看过java中的动态代理, 感觉有点复杂. 需要被代理类实现一个预定好的接口.
虽然很容易理解,但是毕竟多出一个接口需要定义, 阅读起来也不是那么方便.
先贴一下cglib中的代码:

  1. 引入cglib

    <dependency>
     <groupId>cglib</groupId>
     <artifactId>cglib</artifactId>
     <version>3.2.5</version>
    </dependency>
  2. 定义被代理类:

    public class HelloServiceImpl {
     public void sayHello(){
         System.out.println("Hello cglib");
     }
    }
  3. 定义代理类:

    public class HelloMethodInterceptor implements MethodInterceptor {
     @Override
     public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
         System.out.println("Before : " + method.getName());
         Object object = methodProxy.invokeSuper(o, objects);
         System.out.println("After : " + method.getName());
         return object;
     }
    }
  4. 生成对象并调用方法:

    public class Client {
     public static void main(String[] args) {
         Enhancer enhancer = new Enhancer();
         enhancer.setSuperclass(HelloServiceImpl.class);
         enhancer.setCallback(new HelloMethodInterceptor());
         HelloServiceImpl helloServiceImpl = (HelloServiceImpl) enhancer.create();
         helloServiceImpl.sayHello();
     }
    }
  5. 输出:

    Before : sayHello
    Hello cglib
    After : sayHello


并没有很深入的了解,只是简单的跟着敲了一下demo. 等到实际用的时候再来补充体验吧.


   转载规则


《初见cglib》 echi1995 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
使用@PostConstruct修饰的方法执行顺序 使用@PostConstruct修饰的方法执行顺序
看到JSR-250,搜了一下.Spring JSR-250 注释包含三个注释@PostConstruct, @PreDestroy和 @Resource. 先不看@Resource, 单看前两个.在使用过程中,曾有过疑问, @PostCo
下一篇 
Unable to store Job:'todoJobGroup.1183894449946624', because one already exists with this identification. Unable to store Job:'todoJobGroup.1183894449946624', because one already exists with this identification.
在今天迭代上线后,测试突然发现了一个bug.去pro环境看了一下log 2019-08-02 17:52:40.756 ERROR 18408 --- [nio-8084-exec-2] c.g.common.eventbus.EventB
  目录