JDK代理 与 CBLIB代理 总结
JDK代理:
package com.pinus.factory; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; public class BeanFactory implements InvocationHandler { private static Map<Object, Object> map; private BeanFactory() { } /** * 创建BeanFactory实例 */ public static BeanFactory getInstance() { map = new HashMap<Object, Object>(); return new BeanFactory(); } /** * 得到原类型对象 */ @SuppressWarnings("rawtypes") public Object getBean(Class classType) { try { return classType.newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 得到代理类型对象 */ @SuppressWarnings("rawtypes") public Object getProxyBean(Class classType) { Object proxyObject = Proxy.newProxyInstance(classType.getClassLoader(), classType.getInterfaces(), this); Object targetObject = this.getBean(classType); map.put(proxyObject.getClass(), targetObject); return proxyObject; } @Override public Object invoke(Object proxyObject, Method method, Object[] args) throws Throwable { return method.invoke(map.get(proxyObject.getClass()), args); } }
CBLIB代理:
package com.pinus.factory; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class BeanFactory implements MethodInterceptor { private static Map<Object, Object> map; private BeanFactory() { } /** * 创建BeanFactory实例 */ public static BeanFactory getInstance() { map = new HashMap<Object, Object>(); return new BeanFactory(); } /** * 得到原类型对象 */ @SuppressWarnings("rawtypes") public Object getBean(Class classType) { try { return classType.newInstance(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * 得到代理类型对象 */ @SuppressWarnings("rawtypes") public Object getProxyBean(Class classType) { Object proxyObject; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(classType); enhancer.setCallback(this); proxyObject = enhancer.create(); Object targetObject = this.getBean(classType); map.put(proxyObject.getClass(), targetObject); System.out.println(map.size()); return proxyObject; } @Override public Object intercept(Object proxyObject, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { // TODO Auto-generated method stub return method.invoke(map.get(proxyObject.getClass()), args); } }总结:JDK代理:动态生成一个类实现目标对象类型所实现的所有接口,将此类实例化后返回
CGLIB代理:动态生成一个类继承目标对象类型,将此类实例化后返回
方法调用:实际上还是调用原目标对象中的方法,动态代理对象并未使用
Jdk代理和CGLIB代理的区别cglib代理和jdk动态代理区别
总结:静态代理、jdk动态代理、cglib代理cglib代理和jdk动态代理区别
动态代理:JDK动态代理和CGLIB代理的区别cglib代理和jdk动态代理区别
最详细的代理讲解--JDK动态代理和cglib代理cglib代理和jdk动态代理区别
JDK动态代理和 CGLIB代理cglib代理和jdk动态代理区别
Spring入门第三讲 Spring中的代理 静态代理 动态代理(JDK代理) cglib代理(字节码增强) Spring中的AOPspring的静态代理和动态代理
java-动态代理-jdk代理、cglib代理、生成字节码文件.