AOP编程——ProceedingJoinPoint只支持around advice

AOP programming - ProceedingJoinPoint is only supported for around advice

我在部署新方面时遇到此异常:

@Aspect
public class MyAspect {

    @Before("@annotation(PreAuthorizeAccess)")
    public Object tessst(ProceedingJoinPoint joinPoint) throws Throwable {
        for (Object object : joinPoint.getArgs()) {
            int a = 0;
        }
        return joinPoint.proceed();
    }
}

Caused by: java.lang.IllegalArgumentException: ProceedingJoinPoint is only supported for around advice at org.springframework.aop.aspectj.AbstractAspectJAdvice.maybeBindProceedingJoinPoint(AbstractAspectJAdvice.java:414) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE] at org.springframework.aop.aspectj.AbstractAspectJAdvice.calculateArgumentBindings(AbstractAspectJAdvice.java:388) ~[spring-aop-5.1.7.RELEASE.jar:5.1.7.RELEASE]

我想拦截所有用 @PreAuthorizeAccess 注释的方法并更改 myObject 中的某些内容,如下所示:

@PreAuthorizeAccess
public MyObject save(@Param("argument") MyObject myObject) {

Spring AOP 提供了多个建议,BeforeAround 等。通过设置 @Before 建议并使用 ProceedingJoinPoint 检索传递给建议的方法参数,您无意中将两者结合在一起,这是为使用 @Around 建议保留的。因此例外。

来自Spring documentation:

Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception).

Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

要么声明一个之前的建议使用:

@Before("@annotation(PreAuthorizeAccess)")
public void tessst(JoinPoint joinPoint) throws Throwable {
    for (Object object : joinPoint.getArgs()) {
        int a = 0;
    }
}

或者使用 @Around("@annotation(PreAuthorizeAccess)") 而不是 @Before("@annotation(PreAuthorizeAccess)") 将方法调用包装在 @Around 建议中。

虽然根据您提供的片段,我的猜测是 @Before 建议可能更适合您的情况。