1. 拦截器细节
- 前置处理按拦截器列表的顺序执行;
- 后置处理按拦截器列表的逆序执行;
- 后置处理的异常需捕获后统一抛出;
2. 代码示例
public class InterceptorChain {
private List<IInterceptor> interceptorList = new ArrayList<>();
public void registerInterceptor(IInterceptor interceptor) {
interceptorList.add(interceptor);
}
public void beforeHandle(Object obj, Callable task) {
if (CollectionUtils.isEmpty(interceptorList)) {
return;
}
for (IInterceptor interceptor : interceptorList) {
interceptor.beforeHandle(obj, task);
}
}
public void afterHandle(Object obj, Callable task) {
if (CollectionUtils.isEmpty(interceptorList)) {
return;
}
List<Throwable> throwableList = new ArrayList<>;
for(int i = interceptorList.size(); i > -1; i--) {
try {
interceptorList.get(i).afterHandle(obj, task);
} catch (Throwable throwable) {
throwableList.add(throwable);
}
}
ExceptionUtils.throwExceptionIfNotEmpty(throwableList);
}
}
网友评论