拦截器实现的细节

1. 拦截器细节

  1. 前置处理按拦截器列表的顺序执行;
  1. 后置处理按拦截器列表的逆序执行;

  2. 后置处理的异常需捕获后统一抛出;

2. 代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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);
}
}

评论