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;
}
}