无法捕获@afterhrowing advice中@before advice中抛出的异常

6tr1vspr  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(998)

我正在使用 @Before 以及 @AfterThrowing spring aop建议。在before建议中,我正在验证数据,并在验证失败时抛出用户定义的异常。我已经定义了一个 @AfterThrowing ,我希望这将捕获错误以打印所需的其他信息。但出乎意料的是,我没能击中目标 @AfterThrowing 建议。我不确定我做的是否正确,或者springaop不支持这样做。
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();
    }
}
wlwcrazw

wlwcrazw1#

从参考文件@Afterhrowing可以阅读:
请注意,@afterthrowing并不表示常规异常处理回调。具体地说,@afterthrowing advice方法只能从连接点(用户声明的目标方法)本身接收异常,而不能从附带的@after/@afterreturning方法接收异常。
在你的代码里 @Before 通知在实际用户声明的目标方法和引发异常之前执行。控件从此点返回,因此将不会到达 @AfterThrowing 建议
同时也要阅读建议
从springframework5.2.7开始,在同一@aspect类中定义的需要在同一连接点上运行的advice方法根据其advice类型按以下顺序分配优先级:从最高到最低优先级:@about、@before、@after、@afterreturning、@afterthrowing。
你可以通过这个答案(基于 spring-aop-5.3.3 )与 @Around 这样就可以尝试实现您的用例。

相关问题