Spring AOP(六)通知获取参数

转载自 https://blog.csdn.net/Sadlay/article/details/83501875

通知获取参数

在之前AOP的文章中,大部分我们没有给通知传递参数。有时候我们希望能够传递参数给通知。我们只需要子啊切点处加入对应的正则式就可以了。

当然,对于非环绕通知我们还可以使用一个连接点(Pointcut)类型的参数,通过它也可以获取参数。

前置通知中获取参数

切面类MyAspect

package com.lay.springboot_aop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareParents;
import org.aspectj.lang.annotation.Pointcut;

import com.lay.springboot_aop.aspect.pojo.User;
import com.lay.springboot_aop.aspect.validator.UserValidator;
import com.lay.springboot_aop.aspect.validator.impl.UserValidatorImpl;

@Aspect
public class MyAspect {
    @Pointcut("execution(* com.lay.springboot_aop.aspect.service.impl.UserServiceImpl.printUser(..))")
    public void pointCut() {
    }
    
    @Before("pointCut()&&args(user)")
    public void before(JoinPoint point ,User user) {
        Object[] args=point.getArgs();
        User a= (User)args[0];
        System.out.println("print in before"+user.getUserName());
        System.out.println("\nprint in before args = "+a.getUserName());
        System.out.println("before-----------");
    }
    
}

正则式pointCut()&&args(user)中,pointCut()表示启用原来定义切点的规则,并且约定将连接点(目标对象方法)名称为user的参数传递进来。这里要注意,JointPoint类型的参数对于非环绕通知而言,Spring AOP会自动的把它传递到参数U中;对于环绕通知而言,可以使用ProceedingJointPoint类型的参数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值