Sping:AOP-cglib字节码增强

匿名 (未验证) 提交于 2019-12-02 23:32:01
  1. 没有接口,只有实现类。
  2. 采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。
  3. 导入spring的核心包
  4. 上代码:
 package com.fjs.Services;   import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy;  import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;  /* cglib 字节码增强  */ public class MyBeanFactory {     public static Services createService2(){         //目标类         final Services service=new ServicesImpl();         //切面类         final MyAspect aspect=new MyAspect();         //cglib核心类         //创建增强对象         Enhancer enhancer=new Enhancer();         //设置父类         enhancer.setSuperclass(service.getClass());         //设置回调(拦截)         enhancer.setCallback(new MethodInterceptor() {             @Override             public Object intercept(Object Proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {                 /**                  * proxy:                  * om.gyf.service.StudentService$$EnhancerByCGLIB$$fbb8ef26                  * proxy代理对象是StudentService的子类                  */                 aspect.before();                  Object obj=methodProxy.invokeSuper(Proxy,objects);                 aspect.after();                 return obj;             }         });          ServicesImpl proxy= (ServicesImpl) enhancer.create();                  return proxy;     }  /* JDK实现代理  */      public static Services createService() {         //目标类         final Services service = new ServicesImpl();         //切面类         final MyAspect aspect = new MyAspect(); //    public static Object newProxyInstance(ClassLoader loader,类加载器 //                                          Class<?>[] interfaces,接口 //                                          InvocationHandler h)处理          //代理类         Services serviceProxy = (Services) Proxy.newProxyInstance(                 MyBeanFactory.class.getClassLoader(),                 service.getClass().getInterfaces(),                 new InvocationHandler() {                     @Override                     public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {                         //开启事物                         aspect.before();                          //service的返回值                         Object obj = method.invoke(service, args);                          //提交事物                         aspect.after();                           return obj;                     }                 }         );         return serviceProxy;      }  } 
文章来源: https://blog.csdn.net/qq_41601512/article/details/90216163
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!