29. // been evaluated statically before this object was constructed.
30. return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(nextInvocation()); 31. } 32.}
这里把当前的拦截器链以及在拦截器链的位置标志都clone到一个
MethodInvocation对象了,作用是当前的拦截器执行完之后,会继续沿着得到这个拦截器链执行下面的拦截行为,也就是会迭代的调用上面这个proceed: 代码
1. private ReflectiveMethodInvocation nextInvocation() throws CloneNotSupportedException {
2. ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) clone();
3. invocation.currentInterceptorIndex = this.currentInterceptorIndex + 1;
4. invocation.parent = this; 5. return invocation; 6. }
这里的nextInvocation就已经包含了当前的拦截链的基本信息,我们看到在Interceptor中的实现比如TransactionInterceptor的实现中: 代码
1. public Object invoke(final MethodInvocation invocation) throws Throwable {
2. ......//这里是TransactionInterceptor插入的事务处理代码,我们会在后面分析事务处理实现的时候进行分析 3. try {
4. //这里是对配置的拦截器链进行迭代处理的调用 5. retVal = invocation.proceed(); 6. }
7. ......//省略了和事务处理的异常处理代码 ,也是TransactionInterceptor插入的处理 8. else { 9. try {
10. Object result = ((CallbackPreferringPlatformTransactionManager) getTransactionManager()).execute(txAttr, 11. new TransactionCallback() {
12. public Object doInTransaction(TransactionStatus status) {
13. //这里是TransactionInterceptor插入对事务处理的代码
14. TransactionInfo txInfo = prepareTransactionInfo(txAttr, joinpointIdentification, status); 15. //这里是对配置的拦截器链进行迭代处理的调用,接着顺着拦截器进行处理
16. try { 17. return invocation.proceed(); 18. }
19. ......//省略了和事务处理的异常处理代码 ,也是TransactionInterceptor插入的处理 20. }
从上面的分析我们看到了Spring AOP的基本实现,比如Spring怎样得到Proxy,怎样利用JAVA Proxy以及反射机制对用户定义的拦截器链进行处理。