springboot之aop切面execution表达式,@args,@annotation

最近在使用springboot进行切面编程的时候,发现定义切面点有很多种方式,每种方式有每种方式的特点。特此记录

execution表达式

基本语法格式为:execution(<修饰符模式>?<返回类型模式><方法名模式>(<参数模式>)<异常模式>?)除了返回类型模式,方法名模式和参数模式外,其它项都是可选的。 例如:

 	@Pointcut("execution(public * cn.hjljy.*.controller..*.*(..))")
    public void logCut(){}
    @Around("logCut()")
    public Object validateParam(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("进入切面进行验证");
        Object obj = joinPoint.proceed();
        return obj;
    }
复制代码
模式 描述
public public 表示public 级别方法。 可以不写,不写就是所有的方法(public,private,protected等级别的方法)
开头的 * 表示方法返回值的类型 * 表示全部
cn.hjljy.*.controller 表示具体的包名,中间使用*做通配符
.. 表示包以及包下面的子包
* 表示全部
.*(..) 表示全部方法

@args 表达式

args主要是用来限制方法的参数的,args有两种表现形式:@args 和args 使用@args需要通过注解,如果方法里面有参数持有这个注解,就可以。 例如:

 	@Pointcut("@args(cn.hjljy.mlog.common.annotation.MlogLog)")
    public void logCut(){}
    @Around("logCut()")
    public Object validateParam(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("进入切面进行验证");
        Object obj = joinPoint.proceed();
        return obj;
    }
复制代码

如果某个方法例如:

  public void test(MlogCommentEntity entity) {
      //如果entity这个实体类上面有MlogLog这个注解,就会被切面切到。
   }
复制代码

如果是args需要书写方法参数类型并且是配合execution表达式进行的处理例如:

//第一种写法
   @Around("execution( * cn..*.controller..*.*(..))&&args(..,org.springframework.validation.BindingResult)\"")
   public Object validateParam(ProceedingJoinPoint joinPoint) throws Throwable {
       System.out.println("进入切面进行验证");
       Object obj = joinPoint.proceed();
       return obj;
   }
//第二种写法
   @Around("execution( * cn..*.controller..*.*(..))&& args(..,bindingResult)")
   public Object validateParam(ProceedingJoinPoint joinPoint, BindingResult bindingResult) throws Throwable {
       System.out.println("进入切面进行验证");
       Object obj = joinPoint.proceed();
       return obj;
   }
复制代码
模式 描述
两种写法 表示任意参数开头,方法最后一个入参是BindingResult 类型

@annotation 表达式

这个非常的常见,直接通过注解进行的切面。只需要在需要切面的方法上加上对应的注解就可以了。 例如:

	@Pointcut("@annotation(cn.hjljy.mlog.common.annotation.MlogLog)")
    public void logCut(){}
    @Around("logCut()")
    public Object validateParam(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("进入切面进行验证");
        Object obj = joinPoint.proceed();
        return obj;
    }
复制代码

然后在需要进行切面的方法上加上对应的注解就可以了。

猜你喜欢

转载自juejin.im/post/7031058380261163038