我们知道 AspectJ 中的通知方法可以携带参数,例如 @Before 前置通知方法可以携带一个 JoinPoint 类型参数,那么还可以携带其它参数吗?
示例一
@Before(value = "execution(* *..UserServiceImpl.doSome(String))", argNames = "joinPoint,name")
public void beforeSome(JoinPoint joinPoint, String name) {System.out.println("前置增强");Object[] args = joinPoint.getArgs();if (args.length > 0) {System.out.println("前置增强目标方法参数值为:");for (Object arg : args) {System.out.println(arg);}}
}
上面的代码不仅携带了 JoinPoint 类型的参数,还携带了一个 String 类型的参数。会正常执行吗?
// 将通知注解属性 argNames 处理成 argumentNames
public void setArgumentNamesFromStringArray(String... args) {this.argumentNames = new String[args.length];for (int i = 0; i < args.length; i++) {this.argumentNames[i] = StringUtils.trimWhitespace(args[i]);// 校验是否是有效的 Java 标识符if (!isVariableName(this.argumentNames[i])) {throw new IllegalArgumentException("'argumentNames' property of AbstractAspectJAdvice contains an argument name '" +this.argumentNames[i] + "' that is not a valid Java identifier");}}if (this.argumentNames != null) {// 校验数量,默认可以在 argNames 属性中不指定固定的三个参数类型对应的名称,如果指定了就不做处理if (this.aspectJAdviceMethod.getParameterCount() == this.argumentNames.length + 1) {// May need to add implicit join point arg name...Class<?> firstArgType = this.aspectJAdviceMethod.getParameterTypes()[0];if (firstArgType == JoinPoint.class ||firstArgType == ProceedingJoinPoint.class ||firstArgType == JoinPoint.StaticPart.class) {String[] oldNames = this.argumentNames;this.argumentNames = new String[oldNames.length + 1];this.argumentNames[0] = "THIS_JOIN_POINT";System.arraycopy(oldNames, 0, this.argumentNames, 1, oldNames.length);}}}
}public final void calculateArgumentBindings() {// 校验标识为 true 或者没有参数,直接返回if (this.argumentsIntrospected || this.parameterTypes.length == 0) {return;}int numUnboundArgs = this.parameterTypes.length;// 获取实际的参数数量,也就是说,可以不在 argNames 中指定通知方法参数名称Class<?>[] parameterTypes = this.aspectJAdviceMethod.getParameterTypes();// 处理三个固定参数,修改对应索引 joinPointArgumentIndex、joinPointStaticPartArgumentIndexif (maybeBindJoinPoint(parameterTypes[0]) || maybeBindProceedingJoinPoint(parameterTypes[0]) ||maybeBindJoinPointStaticPart(parameterTypes[0])) {numUnboundArgs--;}// 除三个固定参数外 ,还存在其它参数if (numUnboundArgs > 0) {// need to bind arguments by name as returned from the pointcut matchbindArgumentsByName(numUnboundArgs);}this.argumentsIntrospected = true;
}// AbstractAspectJAdvice
private void bindArgumentsByName(int numArgumentsExpectingToBind) {// 未在 argNames 属性中指定通知方法参数名称if (this.argumentNames == null) {// 通过 ASM 获取指定通知方法参数名称this.argumentNames = createParameterNameDiscoverer().getParameterNames(this.aspectJAdviceMethod);}if (this.argumentNames != null) {// 绑定显式参数bindExplicitArguments(numArgumentsExpectingToBind);}else {throw new IllegalStateException("Advice method [" + this.aspectJAdviceMethod.getName() + "] " +"requires " + numArgumentsExpectingToBind + " arguments to be bound by name, but " +"the argument names were not specified and could not be discovered.");}
}
// AbstractAspectJAdvice
private void bindExplicitArguments(int numArgumentsLeftToBind) {Assert.state(this.argumentNames != null, "No argument names available");this.argumentBindings = new HashMap<>();// 获取方法参数长度,与注解属性 argNames 解析的字符串数组长度作比较,不一致抛出异常int numExpectedArgumentNames = this.aspectJAdviceMethod.getParameterCount();if (this.argumentNames.length != numExpectedArgumentNames) {throw new IllegalStateException("Expecting to find " + numExpectedArgumentNames +" arguments to bind by name in advice, but actually found " +this.argumentNames.length + " arguments.");}// So we match in number...int argumentIndexOffset = this.parameterTypes.length - numArgumentsLeftToBind;for (int i = argumentIndexOffset; i < this.argumentNames.length; i++) {this.argumentBindings.put(this.argumentNames[i], i);}// Check that returning and throwing were in the argument names list if// specified, and find the discovered argument types.if (this.returningName != null) {// 参数名称不一致,抛出异常if (!this.argumentBindings.containsKey(this.returningName)) {throw new IllegalStateException("Returning argument name '" + this.returningName +"' was not bound in advice arguments");}else {// 设置目标方法返回值类型Integer index = this.argumentBindings.get(this.returningName);this.discoveredReturningType = this.aspectJAdviceMethod.getParameterTypes()[index];this.discoveredReturningGenericType = this.aspectJAdviceMethod.getGenericParameterTypes()[index];}}if (this.throwingName != null) {if (!this.argumentBindings.containsKey(this.throwingName)) {throw new IllegalStateException("Throwing argument name '" + this.throwingName +"' was not bound in advice arguments");}else {Integer index = this.argumentBindings.get(this.throwingName);this.discoveredThrowingType = this.aspectJAdviceMethod.getParameterTypes()[index];}}// 为 AspectJExpressionPointcut 设置 pointcutParameterNames 和 pointcutParameterTypes 两个属性configurePointcutParameters(this.argumentNames, argumentIndexOffset);
}private void configurePointcutParameters(String[] argumentNames, int argumentIndexOffset) {int numParametersToRemove = argumentIndexOffset;if (this.returningName != null) {numParametersToRemove++;}if (this.throwingName != null) {numParametersToRemove++;}String[] pointcutParameterNames = new String[argumentNames.length - numParametersToRemove];Class<?>[] pointcutParameterTypes = new Class<?>[pointcutParameterNames.length];Class<?>[] methodParameterTypes = this.aspectJAdviceMethod.getParameterTypes();int index = 0;// 小于偏移量,非显式参数,参数名称和 returningName、throwingName 两个字段值一样,也过滤掉for (int i = 0; i < argumentNames.length; i++) {if (i < argumentIndexOffset) {continue;}if (argumentNames[i].equals(this.returningName) ||argumentNames[i].equals(this.throwingName)) {continue;}pointcutParameterNames[index] = argumentNames[i];pointcutParameterTypes[index] = methodParameterTypes[i];index++;}this.pointcut.setParameterNames(pointcutParameterNames);this.pointcut.setParameterTypes(pointcutParameterTypes);
}
在 ReflectiveAspectJAdvisorFactory#getAdvice 中将 adviceMethod 封装成 springAdvice 时,得到注解属性 argNames,不为 null,将其赋值给 AbstractAspectJAdvice 中 arguementNames 字段,接着 AbstractAspectJAdvice#calculateArgumentBindings --> AbstractAspectJAdvice#bindArgumentsByName,此时由于 arguementNames 不为 null 并不会通过 ASM 去读取方法参数名称,执行AbstractAspectJAdvice#bindExplicitArguments 绑定显式参数,为 AbstractAspectJAdvice 中 argumentBindings 赋值,是一个 HashMap,key 为参数名称,value 为参数位置索引,之后执行 AbstractAspectJAdvice#configurePointcutParameters 配置切入点方法参数,固定的三个参数、returningName 和 throwingName 都不算作切入点方法显式参数,接着为 AspectJExpressionPointcut 设置 pointcutParameterNames 和 pointcutParameterTypes 两个属性。
到这里,其实上面的配置都不会报错。
// AspectJExpressionPointcut
private PointcutExpression buildPointcutExpression(@Nullable ClassLoader classLoader) {PointcutParser parser = initializePointcutParser(classLoader);// 封装 PointcutParameter 数组PointcutParameter[] pointcutParameters = new PointcutParameter[this.pointcutParameterNames.length];for (int i = 0; i < pointcutParameters.length; i++) {pointcutParameters[i] = parser.createPointcutParameter(this.pointcutParameterNames[i], this.pointcutParameterTypes[i]);}return parser.parsePointcutExpression(replaceBooleanOperators(resolveExpression()),this.pointcutDeclarationScope, pointcutParameters);
}
// PointcutParser
protected Pointcut resolvePointcutExpression(String expression, Class<?> inScope, PointcutParameter[] formalParameters) {try {PatternParser parser = new PatternParser(expression);parser.setPointcutDesignatorHandlers(pointcutDesignators, world);Pointcut pc = parser.parsePointcut(); // more correctly: parsePointcut(true)validateAgainstSupportedPrimitives(pc, expression);IScope resolutionScope = buildResolutionScope((inScope == null ? Object.class : inScope), formalParameters);pc = pc.resolve(resolutionScope);return pc;} catch (ParserException pEx) {throw new IllegalArgumentException(buildUserMessageFromParserException(expression, pEx));}
}
private IScope buildResolutionScope(Class<?> inScope, PointcutParameter[] formalParameters) {if (formalParameters == null) {formalParameters = new PointcutParameter[0];}// 封装 FormalBinding 数组FormalBinding[] formalBindings = new FormalBinding[formalParameters.length];for (int i = 0; i < formalBindings.length; i++) {formalBindings[i] = new FormalBinding(toUnresolvedType(formalParameters[i].getType()), formalParameters[i].getName(), i);}if (inScope == null) {return new SimpleScope(getWorld(), formalBindings);} else {ResolvedType inType = getWorld().resolve(inScope.getName());ISourceContext sourceContext = new ISourceContext() {public ISourceLocation makeSourceLocation(IHasPosition position) {return new SourceLocation(new File(""), 0);}public ISourceLocation makeSourceLocation(int line, int offset) {return new SourceLocation(new File(""), line);}public int getOffset() {return 0;}public void tidy() {}};return new BindingScope(inType, sourceContext, formalBindings);}
}
// org.aspectj.weaver.patterns.Pointcut
public final Pointcut resolve(IScope scope) {assertState(SYMBOLIC);Bindings bindingTable = new Bindings(scope.getFormalCount());IScope bindingResolutionScope = scope;if (typeVariablesInScope.length > 0) {bindingResolutionScope = new ScopeWithTypeVariables(typeVariablesInScope, scope);}this.resolveBindings(bindingResolutionScope, bindingTable);bindingTable.checkAllBound(bindingResolutionScope);this.state = RESOLVED;return this;
}
// SimpleScope bindings 就是构造 BindingScope 时传入的 formalBindings
public int getFormalCount() {return bindings.length;
}
public Bindings(int count) {this(new BindingPattern[count]);
}
public Bindings(BindingPattern[] bindings) {// BindingPattern 数组this.bindings = bindings;
}
// 校验所有绑定
public void checkAllBound(IScope scope) {// 遍历 BindingPattern 数组,由前面可知数组中元素值为 nullfor (int i = 0, len = bindings.length; i < len; i++) {if (bindings[i] == null) {// 当 FormalBingding 为 隐式类型时,才避免抛出异常if (scope.getFormal(i) instanceof FormalBinding.ImplicitFormalBinding) {bindings[i] = new BindingTypePattern(scope.getFormal(i), false);} else {scope.message(IMessage.ERROR, scope.getFormal(i), "formal unbound in pointcut ");}}}}// SimpleScope
public FormalBinding getFormal(int i) {// 返回构造 BindingScope 时传入的 formalBindings 数组按指定索引对应的元素return bindings[i];
}
接着执行到创建代理,匹配目标对象对应的 Advisor 时,执行 AspectJExpressionPointcut#obtainPointcutExpression,开始对切入点表达式进行解析。先创建一个 PointcutParser,接着利用
前面设置的 pointcutParameterNames 和 pointcutParameterTypes 封装 org.aspectj.weaver.tools.PointcutParameter 数组,然后对切入点表达式进行解析。在 org.aspectj.weaver.tools.PointcutParser#resolvePointcutExpression 中执行到 buildResolutionScope 时,利用 PointcutParameter 数组,封装 FormalBinding 数组,之后执行
Pointcut#resolve,在 checkAllBound 方法中,可以看到,凡是自定义的显式参数,都会报错,抛出异常。
示例二
@Before(value = "execution(* *..UserServiceImpl.doSome(String))")
public void beforeSome(JoinPoint joinPoint, String name) {System.out.println("前置增强");Object[] args = joinPoint.getArgs();if (args.length > 0) {System.out.println("前置增强目标方法参数值为:");for (Object arg : args) {System.out.println(arg);}}
}
通过前面的介绍,未指定 argNames 注解属性时,在 calculateArgumentBindings --> bindArgumentsByName 中,由于 argumentNames 为 null,通过 ASM 读取参数名称,紧接着执行 bindExplicitArguments --> configurePointcutParameters,为 AspectJExpressionPointcut 中 pointcutParameterNames 和 pointcutParameterTypes 赋值。
也就是说,一直到 springAdvice 封装完成,也不会报错。
接着创建代理,AopUtils#canApply 过滤需要的 Advisor,解析切入点表达式,org.springframework.aop.aspectj.AspectJExpressionPointcut#buildPointcutExpression 创建
org.aspectj.weaver.tools.PointcutExpression。由于存在 pointcutParameterNames,会为创建的 PointcutParameter 数组赋值。在 org.aspectj.weaver.tools.PointcutParser#resolvePointcutExpression 中执行具体的解析。buildResolutionScope 方法中,由于存在 PointcutParameter 数组,进一步将其
封装为 FormalBinding 数组,之后封装一个 BindingScope 对象,作为 IScope 返回,之后将 BindingScope 作为参数,执行 Pointcut#resolve --> checkAllBound,开始为
BindingPattern 数组赋值,因为存在显式参数,直接报错。
示例三
@AfterReturning(value = "execution(* *..UserServiceImpl.doThird())", returning = "result", argNames = "obj")
public void afterReturning(Object result) {System.out.println("后置增强: 方法返回值为 --> " + result.toString());
}
为 AbstractAspectJAdvice 设置完 returningName 属性之后,calculateArgumentBindings --> bindArgumentsByName,此时由于 argumentNames 不为 null,在执行 bindExplicitArguments 方法时,发现 returningName 和 argumentNames 对应索引下的名称不一致,抛出异常。
也就是说,当注解 returning 属性和 argNames 属性一致时,即使和方法实际参数名称不一致,也能正常执行。
如果不设置 argNames 属性, 即 AbstractAspectJAdvice 中 argumentNames 字段为 null,此时通过 ASM 读取方法实际参数名称,为 argumentNames 赋值。接着在 bindExplicitArguments 方法中,发现 returning 注解属性配置的名称和方法参数实际参数名称不一致,抛出异常。
@AfterReturning(value = "execution(* *..UserServiceImpl.doThird())", returning = "result")
public void afterReturning(Object result) {System.out.println("后置增强: 方法返回值为 --> " + result.toString());
}
正常情况下, 未指定 argNames 属性,ASM 读取方法实际参数名称,为 argumentNames 赋值。接着执行 bindExplicitArguments --> configurePointcutParameters,过滤掉 returningName 和 throwingName 之后,将 AspectJExpressionPointcut 中 pointcutParameterNames 和 pointcutParameterTypes 都赋值为长度是0的数组。
所以在之后执行切点表达式解析时,PointcutParameter 数组长度为 0,org.aspectj.weaver.patterns.Bindings#checkAllBound 时按不存在显式参数处理。
示例四
@AfterReturning(value = "execution(* *..UserServiceImpl.doThird())", returning = "result")
public void afterReturning(Object result) {System.out.println("后置增强: 方法返回值为 --> " + result.toString());
}
下来看下方法调用时,目标方法的执行结果,是怎么传递给通知方法的?
// AfterReturningAdviceInterceptor
@Override
@Nullable
public Object invoke(MethodInvocation mi) throws Throwable {// 调用连接点方法,得到返回值Object retVal = mi.proceed();// AspectJAfterReturningAdvicethis.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());return retVal;
}
@Override
public void afterReturning(@Nullable Object returnValue, Method method, Object[] args, @Nullable Object target) throws Throwable {// 校验返回值参数类型if (shouldInvokeOnReturnValueOf(method, returnValue)) {invokeAdviceMethod(getJoinPointMatch(), returnValue, null);}
}protected Object invokeAdviceMethod(@Nullable JoinPointMatch jpMatch, @Nullable Object returnValue, @Nullable Throwable ex)throws Throwable {// 在 argBinding 中完成通知方法调用参数的封装,之后调用通知方法return invokeAdviceMethodWithGivenArgs(argBinding(getJoinPoint(), jpMatch, returnValue, ex));
}
// AbstractAspectJAdvice#getJoinPoint
public static JoinPoint currentJoinPoint() {MethodInvocation mi = ExposeInvocationInterceptor.currentInvocation();if (!(mi instanceof ProxyMethodInvocation)) {throw new IllegalStateException("MethodInvocation is not a Spring ProxyMethodInvocation: " + mi);}ProxyMethodInvocation pmi = (ProxyMethodInvocation) mi;JoinPoint jp = (JoinPoint) pmi.getUserAttribute(JOIN_POINT_KEY);if (jp == null) {// 创建 JoinPoint 对象jp = new MethodInvocationProceedingJoinPoint(pmi);pmi.setUserAttribute(JOIN_POINT_KEY, jp);}return jp;
}
// AbstractAspectJAdvice
protected Object[] argBinding(JoinPoint jp, @Nullable JoinPointMatch jpMatch,@Nullable Object returnValue, @Nullable Throwable ex) {// 校验过会直接返回calculateArgumentBindings();// AMC start// 封装通知方法调用参数Object[] adviceInvocationArgs = new Object[this.parameterTypes.length];int numBound = 0;// 不存在固定参数,初始值为 -1if (this.joinPointArgumentIndex != -1) {adviceInvocationArgs[this.joinPointArgumentIndex] = jp;numBound++;}else if (this.joinPointStaticPartArgumentIndex != -1) {adviceInvocationArgs[this.joinPointStaticPartArgumentIndex] = jp.getStaticPart();numBound++;}if (!CollectionUtils.isEmpty(this.argumentBindings)) {// binding from pointcut matchif (jpMatch != null) {PointcutParameter[] parameterBindings = jpMatch.getParameterBindings();for (PointcutParameter parameter : parameterBindings) {String name = parameter.getName();Integer index = this.argumentBindings.get(name);adviceInvocationArgs[index] = parameter.getBinding();numBound++;}}// binding from returning clauseif (this.returningName != null) {Integer index = this.argumentBindings.get(this.returningName);// 赋值adviceInvocationArgs[index] = returnValue;numBound++;}// binding from thrown exceptionif (this.throwingName != null) {Integer index = this.argumentBindings.get(this.throwingName);adviceInvocationArgs[index] = ex;numBound++;}}if (numBound != this.parameterTypes.length) {throw new IllegalStateException("Required to bind " + this.parameterTypes.length +" arguments, but only bound " + numBound + " (JoinPointMatch " +(jpMatch == null ? "was NOT" : "WAS") + " bound in invocation)");}return adviceInvocationArgs;
}protected Object invokeAdviceMethodWithGivenArgs(Object[] args) throws Throwable {Object[] actualArgs = args;if (this.aspectJAdviceMethod.getParameterCount() == 0) {actualArgs = null;}try {ReflectionUtils.makeAccessible(this.aspectJAdviceMethod);return this.aspectJAdviceMethod.invoke(this.aspectInstanceFactory.getAspectInstance(), actualArgs);}catch (IllegalArgumentException ex) {throw new AopInvocationException("Mismatch on arguments to advice method [" +this.aspectJAdviceMethod + "]; pointcut expression [" +this.pointcut.getPointcutExpression() + "]", ex);}catch (InvocationTargetException ex) {throw ex.getTargetException();}
}
可以看到,由于是后置通知,在调用完连接点方法,即目标方法之后,发起后置通知方法的调用,会创建一个 MethodInvocationProceedingJoinPoint,作为 JoinPoint 对象,由于通知方法中并无 JoinPoint 参数,所以在 argBinding 方法中封装通知方法调用参数时,并不会加入这个 JoinPoint 对象。封装完通知方法参数数组,利用反射调用通知方法。
这样,就完成了 @AfterReturning 注解下通知方法可以携带一个目标方法返回值参数的实现。
如果是 @Before 注解,就会用到这个 MethodInvocationProceedingJoinPoint 对象,在第一次调用 calculateArgumentBindings 方法时,对三个固定参数的判断,就会修改 joinPointArgumentIndex 和 joinPointStaticPartArgumentIndex 索引。所以封装通知方法参数数组时就会在第一个位置加上这个 MethodInvocationProceedingJoinPoint 对象。
// MethodInvocationProceedingJoinPoint
@Override
public Object[] getArgs() {if (this.args == null) {this.args = this.methodInvocation.getArguments().clone();}return this.args;
}
可以看到,当获取目标方法参数时,其实还是委托给调用时封装的 MethodInvocation 来获取。
总结
总结一下,就是 AspectJ 中通知方法虽然可以携带参数,但是携带的参数是有限制的,自己随意指定的参数,运行时会报错。从调用的角度考虑,通知方法的调用,是通过拦截器来实现的,目标方法发起调用后,并不会传递通知方法参数,所以这里显式指定的参数就失去了意义。
修改三个固定参数、过滤 returningName 和 throwingName 都是在 spring 中完成的。AspectJExpressionPointcut 是连接 spring 和 AspectJ 的桥梁,如果 AspectJExpressionPointcut
中设置了 pointcutParameterNames 和 pointcutParameterTypes 两个属性,则在解析切入点表达式时,会将这两个属性封装成 org.aspectj.weaver.tools.PointcutParameter 数组,供
AspectJ 使用。
MethodInvocationProceedingJoinPoint 是 spring 对 org.aspectj.lang.JoinPoint 的实现。调用通知方法时参数的封装也是在 spring 中完成的。也就是说,AspectJ 中通知注解提供了 argNames 和 returning
等属性,但是怎么使用这些属性是由 spring 来实现的。