jdk和cglib动态代理
1.jdk动态代理
package com.yqg.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * @author yqg * @date 2019-02-18 22:04 */ public class JdkProxy implements InvocationHandler { private Object target; /** * 绑定业务对象,并返回一个代理类 */ public Object bind(Object target){ this.target = target; return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this); } /** * * @param proxy * @param method * @param args * @return * @throws Throwable */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("你好,小庆"); Object result = method.invoke(target,args); System.out.println("要好好学习哟"); return result; } }
@org.junit.Test public void JdkTest(){ People people = new QingGuo(); JdkProxy jdkProxy = new JdkProxy(); People qingguo = (People) jdkProxy.bind(people); qingguo.drink(); qingguo.eat(); }
2.cglib代理
package com.yqg.proxy; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * @author yqg * @date 2019-02-18 22:05 */ public class CgLibProxy implements MethodInterceptor { private Object target; /** * * 绑定业务对象 */ public Object getInstance(Object target){ this.target = target; /** * 创建增加器,设置代理类的父类和回调方法 */ Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.target.getClass()); enhancer.setCallback(this); return enhancer.create(); } public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("cglib代理"); return methodProxy.invokeSuper(o,objects); } }
@org.junit.Test public void CglibTest(){ People people = new QingGuo(); CgLibProxy cgLibProxy = new CgLibProxy(); People p = (People) cgLibProxy.getInstance(people); p.eat(); p.drink(); }
3.两者区别
jdk动态代理使用反射机制,cglib使用的是字节码机制,前者属于java包,后者属于spring 框架。