码迷,mamicode.com
首页 > 其他好文 > 详细

cglib 动态代理

时间:2016-05-16 19:55:09      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

JDK的动态代理比较慢,可以使用cglib的代理,速度比较快:

package cn.demo02;

 

import java.lang.reflect.Method;

import java.util.zip.CheckedInputStream;

 

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.config.BeanPostProcessor;

import org.springframework.cglib.proxy.Enhancer;

import org.springframework.cglib.proxy.MethodInterceptor;

import org.springframework.cglib.proxy.MethodProxy;

public class PostBean implements BeanPostProcessor {

         @Override

         public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

                  return bean;

         }

 

         @Override

         public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

                  if (bean instanceof Child) {

                           // 对Bean进行 cg(Code generation )lib动态代理

                           Object proxyBean = Enhancer.create(bean.getClass(), new MethodInterceptor() {

                                    @Override

                                    public Object intercept(Object proxyBean, Method method, Object[] args, MethodProxy methodProxy)

                                                      throws Throwable {

                                             if (method.getName().equals("say")) {

                                                      System.err.println("say is beging...");

                                                      Object obj = methodProxy.invokeSuper(proxyBean, args);

                                                      System.err.println("say is over...");

                                                      return obj;

                                             } else {

                                                      // 直斥放行

                                                      return method.invoke(bean, args);                                          }

                                    }

                           });

                           return proxyBean;

                  }

                  return bean;

         }

}

cglib 动态代理

标签:

原文地址:http://www.cnblogs.com/fujilong/p/5499133.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!