首页 > 编程语言 > 详细

通过cglab 实现 Spring AOP

时间:2019-10-26 17:21:34      阅读:83      评论:0      收藏:0      [点我收藏+]
    • 1新建一个目标类

      public class StudentService {

      public void delete(){
      System.out.println("删除学生");
      }
      public void add(){ System.out.println("添加学生"); }
      public void update(){
      System.out.println("更新学生");
      }
      }

       切面类:  增强代码与切入点结合
      public class MyAspect {
      public void before(){
      System.out.println("开启事务");
      }
      public void after(){
      System.out.println("提交事务");
      }
      }

      2.新建一个工厂类

      public class MyBeanFactory {

      public static  StudentService createStudentService(){
      //1创建对象
      final StudentService studentService= new StudentService();
      System.out.println(studentService);
      //2声明切面类对象
      final MyAspect aspect=new MyAspect();
      //3 创建增强对象
      Enhancer enhancer= new Enhancer();
      //4 设置父类
      enhancer.setSuperclass(studentService.getClass());
      //设置回调 拦截
      enhancer.setCallback(new MethodInterceptor() {
      @Override
      public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
      /**
      * class com.zz.service.StudentService$$EnhancerByCGLIB$$c7d7b405
      * org.springframework.cglib.proxy.MethodProxy@53bbfa
      */

      // System.out.println(o.getClass());
      System.out.println(methodProxy);

      aspect.before();

      //放行

         Object retObj = methodProxy.invokeSuper(proxy,args);
      aspect.after();
      System.out.println("拦截....");
      return retObj;
      }
      });

      //创建代理对象

      StudentService serviceProxy = (StudentService) enhancer.create();
      // System.out.println(proxyService);

      return serviceProxy;
      }
      }
    • 测试结果:由cglab 创建对象并实现成功
    • 技术分享图片

       

       

通过cglab 实现 Spring AOP

原文:https://www.cnblogs.com/orangezhangzz/p/11743813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!