面试官:Spring AOP有哪些通知类型,它们的执行顺序是怎样的?

前言

这篇比较简单,但是群友反馈面试被问到了,关键还没答出来,而且还是项目中用的比较多的技术点。还是要在平时开发中有一丢丢好奇心,多点进去看看代码啊!

通知类型

在基于Spring AOP编程的过程中,基于AspectJ框架标准,spring中定义了五种类型的通知,它们分别是:

  • 前置通知 (@Before) 。

  • 返回通知 (@AfterReturning) 。

  • 异常通知 (@AfterThrowing) 。

  • 后置通知 (@After)。

  • 环绕通知 (@Around) :(优先级最高)

通知执行顺序

将上面的所有通知类型写入同一个切面中,它的执行顺序为:

图片

代码展示

package com.cy.pj.common.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.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class SysTimeAspect {

 /**
  * 切入点
  */
 @Pointcut("bean(sysMenuServiceImpl)")
 public void doTime(){}

 @Before("doTime()")
 public void doBefore(JoinPoint jp){
  System.out.println("time doBefore()");
 }
 @After("doTime()")
 public void doAfter(){//类似于finally{}代码块
  System.out.println("time doAfter()");
 }
 /**核心业务正常结束时执行
  * 说明:假如有after,先执行after,再执行returning*/
 @AfterReturning("doTime()")
 public void doAfterReturning(){
  System.out.println("time doAfterReturning");
 }
 /**核心业务出现异常时执行
  * 说明:假如有after,先执行after,再执行Throwing*/
 @AfterThrowing("doTime()")
 public void doAfterThrowing(){
  System.out.println("time doAfterThrowing");
 }
 @Around("doTime()")
 public Object doAround(ProceedingJoinPoint jp)
   throws Throwable{
  System.out.println("doAround.before");
  try {
  Object obj=jp.proceed();
  return obj;
  }catch(Throwable e) {
  System.out.println("doAround.error-->"+e.getMessage());
  throw e;
  }finally {
  System.out.println("doAround.after");
  }
 }

}

代码正常结束

图片

代码出现异常

图片

文末福利

需要更多教程,微信扫码即可
   

                   别忘了扫码领取资料哦                 
【高清学习线路图】和【全套学习视频及相关资料】

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值