How does Spring know that ThrowsAdvice.afterThrowing needs to be called?

How does Spring know that ThrowsAdvice.afterThrowing needs to be called?

I found documentation on the class here but I was wondering if anyone has an elegant explanation of how exactly reflection is used to look for that “afterThrowing” method specificially. I just want to see the code that does that so I can understand it better.

You’re looking at very old documentation (though the current one doesn’t say much more).

Spring uses a ThrowsAdviceInterceptor to handle ThrowsAdvice. You can find version 4.1.4.RELEASE source code here.

Its constructor

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() + "]");
    }
}

scans for appropriate methods and registers them. It then wraps the target method invocation

@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;
    }
}

and invokes the handler if an exception is thrown.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值