文章目录
cglib动态代理
cglib是基于继承的方式实现的
是继承目标类从而产生代理类
springaop底层使用的就是cglib的动态代理
package com.itheima.cjlibproxy; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * @author healer * @Description CglibProxyUtils * @data 2024-06-08 15:21 */ public class CglibProxyUtils { public static Object createProxy(Object targetClass) { // 创建一个 enhancer Enhancer enhancer = new Enhancer(); // 需要指定创建出来的代理类的父类 enhancer.setSuperclass(targetClass.getClass()); // 增强 enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { long start = System.currentTimeMillis(); Object result = method.invoke(targetClass, args); long end = System.currentTimeMillis(); System.out.println("-------->方法耗时:" + (end - start) + "ms"); return result; } }); // 创建代理对象 return enhancer.create(); } }
package com.itheima.cjlibproxy; import com.itheima.jdkProxy.JdkProxyUtil; import com.itheima.service.DeptService; import com.itheima.service.impl.DeptServiceImpl; /** * @author healer * @Description CglibProxyDemo * @data 2024-06-08 15:29 */ public class CglibProxyDemo { public static void main(String[] args) { DeptService deptService = new DeptServiceImpl(); DeptService proxyDeptService = (DeptService) CglibProxyUtils.createProxy(deptService); proxyDeptService.update(); } }
还没有评论,来说两句吧...