AspectJ表达式

本文详细介绍了AspectJ的表达式格式,包括如何匹配不同方法以及各种通配符的使用。同时,文章讲解了AOP的四种增强方式:before、after-throwing、after和after-returning,以及环绕增强的@Around注解的使用。在环绕增强中,重点阐述了 ProceedingJoinPoint 的应用和异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AspectJ表达式

常见格式: execution(再写其它内容)  表示匹配某个方法的执行
	小括号中的其他内容,其实跟我们以前的方法声明语法差不多。只不过支持 * (通配符) 和  ..(表示任意参数)
	
public void *()  
	表示 所有无参的返回值类型是void的任意的public 方法。
public * com.example.spring.aop.service.impl.*Impl.*(..))
	表示com.example.spring.aop.service.impl包下面,所有以Impl结尾的类中,所有public类型的方法。
public * com.example.spring.aop.service.impl.*Impl.m*(..))
	表示com.example.spring.aop.service.impl包下面,所有以Impl结尾的类中,所有public类型的以m开头的方法。
public * com.example..service.impl.*Impl.m*(..)
	表示com.example.service.impl包下面、
		com.example.(任意层级).service.impl包下面,
		所有以Impl结尾的类中,所有public类型的以m开头的方法。

参考资料:https://www.cnblogs.com/duanxz/p/5217689.html

增强方式

  <aop:before> 表示前置增强
  		@Before
  <aop:after-throwing>
  		@AfterThrowing
  		当目标方法执行过程中,抛出异常的时候会执行这里的逻辑。 要想捕获异常类型,可以使用Exception类型的参数,同时使用throwing来绑定形参的名字。
  <aop:after>
  		@After 目标方法执行后(不论是否抛出异常)
  <aop:after-returning>
  		@AfterReturning 目标方法成功执行(有了返回值)后。 
  <aop:around> 【环绕:万金油】
  		@Around
  		

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

 /*
    对于around环绕增强来说,参数类型必须是ProceedingJoinPoint 类型。返回值类型必须是Object类型。
     */
    @Around(value = "execution(public * com.example..service.impl.*Impl.*(..))")
    public  Object m3(ProceedingJoinPoint point){
        Object[] args = point.getArgs();//调用目标方法时传递的实参。

        System.out.println("@Before这里写前置的功能......");

        try {
            Object result =null;
            try {
                result = point.proceed(args);//传递实参,调用目标方法
            }finally {
                System.out.println("是After的执行逻辑....");
            }

            System.out.println("是AfterReturning的执行逻辑.....");
            return result;
        } catch (Throwable throwable) {
//             throwable.printStackTrace(); //表示目标方法执行过程中发生了异常。
            System.out.println("相当于AfterThrowing"+throwable.getMessage());


        }
        return null;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值