zoukankan      html  css  js  c++  java
  • spring学习 十四 注解AOP 通知传递参数

    我们在对切点进行增强时,不建议对切点进行任何修改,因此不加以使用@PointCut注解打在切点上,尽量只在Advice上打注解(Before,After等),如果要在通知中接受切点的参数,可以使用JoinPoint或者ProceedingJoinPoint

    在Spring AOP中可以通过两种方式传递参数给Advice(通知)  

    (1)通过接受JoinPoint(非环绕通知)或ProceedingJoinPoint(环绕通知)参数,其实ProceedingJoinPoint是JointPoint的子接口

    (2) 还可以直接 接收与切入点方法执行有关的对象,比如切入点方法参数、切入点目标对象(target)、切入点代理对象(this)等。

    第一步创建切面类

    package com.airplan.pojo;
    
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.springframework.stereotype.Component;
    
    @Component("advice")
    @Aspect
    public class Advice {
    
            @After("execution(* com.airplan.pojo.PointCutClass.*(..))")
            public void myafter(JoinPoint jp){
                System.out.println("前置通知");
            }
        
    }

    第二步创建切点类,并没有在任何切点上打上@PointCut注解,也就是核心关注点并不会感知到增强

    package com.airplan.pojo;
    
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;
    
    @Component("pointCutClass")
    public class PointCutClass {
        
        public void pointCutFun() {
            
            System.out.println("切点执行");
        }
        
        public void pointCutFun02(String name) {
            System.out.println("切点执行");
        }
        
        
    }

    第三步;测试代码

    package com.airplan.test;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.airplan.pojo.Advice;
    import com.airplan.pojo.PointCutClass;
    
    public class AopDemo {
        public static void main(String[] args) {
            ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
            PointCutClass pc = ac.getBean("pointCutClass",PointCutClass.class);
            pc.pointCutFun02("张三");
            //pc.pointCutFun();
            
        }
    }

     

    JoinPoint解说:

    访问目标方法最简单的做法是定义增强处理方法时,将第一个参数定义为JoinPoint类型,当该增强处理方法被调用时,该JoinPoint参数就代表了织入增强处理的连接点。JoinPoint里包含了如下几个常用的方法:

    • Object[] getArgs:返回目标方法的参数

    • Signature getSignature:返回目标方法的签名

    • Object getTarget:返回被织入增强处理的目标对象

    • Object getThis:返回AOP框架为目标对象生成的代理对象

  • 相关阅读:
    链表栈
    C# TCP应用编程二 同步TCP应用编程
    C# TCP应用编程一 概述
    C# 网络流
    远程连接 出现身份验证错误,要求的函数不受支持(这可能是由于CredSSP加密Oracle修正)
    C#线程Thread类
    C# 通过Internet搜索网络资源
    正则表达式
    C#文件的读写
    微服务实战
  • 原文地址:https://www.cnblogs.com/cplinux/p/9742898.html
Copyright © 2011-2022 走看看