spring aop

奋斗吧
奋斗吧
擅长邻域:未填写

标签: spring aop Java博客 51CTO博客

2023-06-22 18:24:07 254浏览

spring aop,切面表达式execution表达式基本语法格式为:execution(<修饰符模式>?<返回类型模式><方法名模式>(<参数模式>)<异常模式>?)除了返回类型模式,方法名模式和参数模式外,其它项都是可选的。例如:@Pointcut("execution(public*cn.hjljy.*.controller..*.*(..))"


切面表达式


execution表达式

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

// com下所有方法
@Pointcut("execution(* com..*.*(..))")	
	

@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;
    }

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





好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695