AOP优先级踩坑:Required to bind 2 arguments, but only bound 1 (JoinPointMatch was NOT

2024-08-24 21:49:20 浏览数 (1)

故事背景

在一个Spring的项目中,想做2个AOP切面,分别为AspectA与AspectB,并且AspectA的优先级要比AspectB的高,于是想当然地在AspectA加上注解@Order(Ordered.HIGHEST_PRECEDENCE),在AspectB加上注解@Order

因此工程启动后,报错:Required to bind 2 arguments, but only bound 1 (JoinPointMatch was NOT bound in invocation)。

错误栈为:

代码语言:java复制
java.lang.IllegalStateException: Required to bind 2 arguments, but only bound 1 (JoinPointMatch was NOT bound in invocation)
	at org.springframework.aop.aspectj.AbstractAspectJAdvice.argBinding(AbstractAspectJAdvice.java:596) ~[spring-aop-5.3.24.jar:5.3.24]
	at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:624) ~[spring-aop-5.3.24.jar:5.3.24]
	at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:72) ~[spring-aop-5.3.24.jar:5.3.24]
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175) ~[spring-aop-5.3.24.jar:5.3.24]
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:763) ~[spring-aop-5.3.24.jar:5.3.24]
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:708) ~[spring-aop-5.3.24.jar:5.3.24]

解决方案

高优先级的AspectA的优先级值,要至少要大于Integer.MIN_VALUE 1,即@Order(Integer.MIN_VALUE 2)@Order(Ordered.HIGHEST_PRECEDENCE 2)

代码语言:java复制
@Aspect
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE   2)
public class AspectA {
    @Around("@annotation(catTransaction)")
    public Object aroundMethod(ProceedingJoinPoint pjp, CatTransaction catTransaction) throws Throwable {
        // 获取注解信息
        System.out.println("aspectA");
        return pjp.proceed();
    }
}

原因分析

SpringAop为在容器启动时,事先创建内部的拦截器类ExposeInvocationInterceptor,它的优先级被设置为最高:Integer.MIN_VALUE 1。源码如下:

代码语言:java复制
@SuppressWarnings("serial")
public final class ExposeInvocationInterceptor implements MethodInterceptor, PriorityOrdered, Serializable {
	...
	@Override
	public int getOrder() {
		return PriorityOrdered.HIGHEST_PRECEDENCE   1;
	}
	...	

因此,各种AOP的拦截器类,包括Spring内部使用的,以及我们自定义的拦截器类,都会被扫描放到集合容器中,并且按照优先级有低到高去排序。如果我们的自定义切面类被设置的小于等于Integer.MIN_VALUE 1,就会使得ExposeInvocationInterceptor的优先级被动调低了,不能率先去执行其增强逻辑,从而引发内部异常

有关ExposeInvocationInterceptor的原理,请参阅ExposeInvocationInterceptor的原理

0 人点赞