无法捕获@AfterThrowing 建议中@Before 建议中抛出的异常

问题描述

我正在使用 @Before@AfterThrowing Spring AOP 建议。在 before 建议中,我正在验证数据并在验证失败时抛出用户定义的异常。由于我已经定义了 @AfterThrowing,我希望这会捕获错误以打印我需要的其他信息。但出乎意料的是,我无法点击 @AfterThrowing 建议。我不确定我是否正确执行或 Spring AOP 不支持此操作。

Spring 配置类

package configurations;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoproxy;

@Configuration
@ComponentScans({
    @ComponentScan(value = "beans"),@ComponentScan(value = "aspects")
})
@ComponentScan(basePackages = {"exceptions"})
@EnableAspectJAutoproxy(proxyTargetClass = true)
public class SpringConfiguration {}

员工类

package beans;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

@Component("employee")
//@DependsOn("fullName")
public class Employee implements Comparable<Employee>,Serializable,Cloneable {
    private int id;
    private String userId;
    private String email;
    
    @Autowired(required = false)
    private FullName fullName;
    
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getUserId() { return userId; }
    public void setUserId(String userId) { this.userId = userId; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public FullName getFullname() { return fullName; }
    public void setFullname(FullName fullname) { this.fullName = fullname; }
    
    @Override
    public String toString() {
        return "Employee [id=" + id + ",userId=" + userId + ",email=" + email + ",fullname=" + fullName + "]";
    }
    
    public int compareto(Employee secondEmployee) {
        return Integer.compare(this.id,secondEmployee.id); 
    }
}

员工方面

package aspects;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
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;

import exceptions.DataOverflowException;
import exceptions.NumberUnderflowException;

@Component
@Aspect
public class EmployeeAspect {
    
    @Before(value="execution(* beans.Employee.set*(..))")
    public void before(JoinPoint joinPoint) throws  Exception{
        List<Object> inputArguments = Arrays.asList(joinPoint.getArgs());
        for(Object argument : inputArguments) {
            switch(argument.getClass().getName()) {
                case "java.lang.String" : {
                    String inputString = (String) argument;
                    if(inputString.length() > 20) 
                        throw new DataOverflowException(joinPoint.getSignature().toString() +" is having excess input information to store.");
                    else
                        break;
                }
                case "java.lang.int" : {
                    int inputNumber = (int) argument;
                    if(inputNumber < 1) 
                        throw new NumberUnderflowException(joinPoint.getSignature().toString() +" is not meeting minimun input information to store.");
                    else
                        break;
                }
            }
        }
    }

    @Around("execution(* beans.Employee.*(..))")
    public void invoke(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Method with Signature :: "+ joinPoint.getSignature() + " having data "+ joinPoint.getTarget() + " invoked");
        joinPoint.proceed(joinPoint.getArgs());
        System.out.println("Method with Signature :: "+ joinPoint.getSignature() + " having data "+ joinPoint.getTarget() + " completed Successfully");
    }
    
    @AfterThrowing(pointcut = "execution(* *(..))",throwing= "error")
    public void afterThrowing(JoinPoint joinPoint,Exception error) {
        System.out.println("===============ExceptionAspect============");
    }

}

测试类

package clients;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import beans.Employee;
import configurations.SpringConfiguration;

public class TestClientA {
    public static void main(String[] args) {
        ConfigurableApplicationContext springContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        Employee empl = springContext.getBean(Employee.class);
        empl.setEmail("vineel.pellella@infor.com");
        springContext.close();
    }
}

解决方法

从参考文档 @AfterThrowing 可以阅读:

注意@AfterThrowing 并不表示一般异常 处理回调。具体来说,@AfterThrowing 建议方法是 只应该从连接点接收异常(用户声明的 目标方法)本身,但不是来自随附的 @After/@AfterReturning 方法。

在您的代码中,@Before 建议在实际用户声明的目标方法之前执行并引发异常。控制权从此时返回,因此不会到达 @AfterThrowing 通知

还要通过 advice ordering

从 Spring Framework 5.2.7 开始,通知方法定义在相同的 需要在同一连接点运行的@Aspect 类被分配 优先级基于他们的建议类型,按以下顺序,从 最高到最低优先级:@Around、@Before、@After、 @AfterReturning,@AfterThrowing。

您可以通过 this answer(基于 spring-aop-5.3.3)和 @Around 来尝试实现您的用例。