请澄清以下内容:问题是:为什么先执行@AfterThrowing 建议然后打印异常。根据定义,我应该首先看到异常,然后是 @AfterThrowing
public class LoggingAspect {
@AfterThrowing(value = "execution(public void setName(String))")
public void afterSetNameAdvice(JoinPoint joinPoint) {
System.out.println("After:"+joinPoint.toString());
}
@Before(value = "execution(public void setName(String))")
public void beforeSetNameAdvice(JoinPoint joinPoint) {
System.out.println("Before:"+joinPoint.toString());
}
SetName Method:
public void setName(String name) {
this.name = name;
throw(new ArithmeticException());
}
Output:
Before:execution(void com.spring.Employee.setName(String))
After:execution(void com.spring.Employee.setName(String))
Exception in thread "main" java.lang.ArithmeticException
at com.spring.Employee.setName(Employee.java:41)
编辑帖子并在下面添加答案我相信这是答案,但我不确定。请有人确认。在内部,Spring 创建了扩展实际目标类的代理类(您有 Join 点)。覆盖连接点方法,实现 AOP 概念。
代理类中的覆盖连接点:
setName(){
Call @Before Advice
Call Join Point -- 此处最初抛出异常。
Call @AfterThrowing Advice
//Frame work 不能先抛出异常,因为它丢失了在覆盖的 setName() 方法中运行 @AfterThrowing Advice 的句柄。所以首先执行@After Throwing Advice并抛出异常
}