Spring如何知道需要调用ThrowsAdvice.afterThrowing?

时间:2015-04-02 17:42:35

标签: spring

Spring如何知道需要调用ThrowsAdvice.afterThrowing?

我发现了documentation on the class here,但我想知道是否有人对如何使用反射进行精确的解释,以及#34;之后的推测"具体方法。我只是想看看能够做到这一点的代码,以便我能更好地理解它。

指向某些源代码的链接就足够了。

1 个答案:

答案 0 :(得分:2)

您正在查看非常旧的文档(尽管current one并未提及更多信息)。

Spring使用ThrowsAdviceInterceptor来处理ThrowsAdvice。您可以找到版本4.1.4.RELEASE源代码here

它的构造函数

public ThrowsAdviceInterceptor(Object throwsAdvice) {
    Assert.notNull(throwsAdvice, "Advice must not be null");
    this.throwsAdvice = throwsAdvice;

    Method[] methods = throwsAdvice.getClass().getMethods();
    for (Method method : methods) {
        if (method.getName().equals(AFTER_THROWING) &&
                (method.getParameterTypes().length == 1 || method.getParameterTypes().length == 4) &&
                Throwable.class.isAssignableFrom(method.getParameterTypes()[method.getParameterTypes().length - 1])
            ) {
            // Have an exception handler
            this.exceptionHandlerMap.put(method.getParameterTypes()[method.getParameterTypes().length - 1], method);
            if (logger.isDebugEnabled()) {
                logger.debug("Found exception handler method: " + method);
            }
        }
    }

    if (this.exceptionHandlerMap.isEmpty()) {
        throw new IllegalArgumentException(
                "At least one handler method must be found in class [" + throwsAdvice.getClass() + "]");
    }
}

扫描适当的方法并注册它们。然后它包装目标方法调用

@Override
public Object invoke(MethodInvocation mi) throws Throwable {
    try {
        return mi.proceed();
    }
    catch (Throwable ex) {
        Method handlerMethod = getExceptionHandler(ex);
        if (handlerMethod != null) {
            invokeHandlerMethod(mi, ex, handlerMethod);
        }
        throw ex;
    }
}

并在抛出异常时调用处理程序。