Spring源码解析(12)之事务源码分析(下)

        接下来我们会分析事务代理对象调用流程,如果还没有看过我spring源码分析上篇的同学,大家最好是先去看下对应创建事务代理对象的流程,然后再来学习事务代理对象的调用流程。

一、调用代理对象流程

        1.1org.springframework.aop.framework.JdkDynamicAopProxy#invoke

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		MethodInvocation invocation;
		Object oldProxy = null;
		boolean setProxyContext = false;

		TargetSource targetSource = this.advised.targetSource;
		Class<?> targetClass = null;
		Object target = null;

		try {
			if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
				// The target does not implement the equals(Object) method itself.
				return equals(args[0]);
			}
			else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
				// The target does not implement the hashCode() method itself.
				return hashCode();
			}
			else if (method.getDeclaringClass() == DecoratingProxy.class) {
				// There is only getDecoratedClass() declared -> dispatch to proxy config.
				return AopProxyUtils.ultimateTargetClass(this.advised);
			}
			else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
					method.getDeclaringClass().isAssignableFrom(Advised.class)) {
				// Service invocations on ProxyConfig with the proxy config...
				return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
			}

			Object retVal;
            // 暴露代理对象
			if (this.advised.exposeProxy) {
				// Make invocation available if necessary.
				oldProxy = AopContext.setCurrentProxy(proxy);
				setProxyContext = true;
			}

			// May be null. Get as late as possible to minimize the time we "own" the target,
			// in case it comes from a pool.
			target = targetSource.getTarget();
			if (target != null) {
				targetClass = target.getClass();
			}

			// 把增强器转换为方法链条
			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

			// Check whether we have any advice. If we don't, we can fallback on direct
			// reflective invocation of the target, and avoid creating a MethodInvocation.
			if (chain.isEmpty()) {
				// We can skip creating a MethodInvocation: just invoke the target directly
				// Note that the final invoker must be an InvokerInterceptor so we know it does
				// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
				Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                // 拦截器链为空,直接通过反射进行调用
				retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
			}
			else {
				// 创建反射方法调用对象
				invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
				// 通过方法拦截器进行拦截调用
				retVal = invocation.proceed();
			}

			// Massage return value if necessary.
			Class<?> returnType = method.getReturnType();
			if (retVal != null && retVal == target &&
					returnType != Object.class && returnType.isInstance(proxy) &&
					!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
				// Special case: it returned "this" and the return type of the method
				// is type-compatible. Note that we can't help if the target sets
				// a reference to itself in another returned object.
				retVal = proxy;
			}
			else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
				throw new AopInvocationException(
						"Null return value from advice does not match primitive return type for: " + method);
			}
			return retVal;
		}
		finally {
			if (target != null && !targetSource.isStatic()) {
				// Must have come from TargetSource.
				targetSource.releaseTarget(target);
			}
			if (setProxyContext) {
				// Restore old proxy.
				AopContext.setCurrentProxy(oldProxy);
			}
		}
	}

  1.2org.springframework.aop.framework.ReflectiveMethodInvocation#proceed

	@Override
	public Object proceed() throws Throwable {
		//	当前下标从-1开始,若当前索引值=执行到最后一个拦截器的下标,就执行目标方法
		if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
			return invokeJoinpoint();
		}
        
        // 获取我们的方法拦截器(TransactionInterceptor)
		Object interceptorOrInterceptionAdvice =
				this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
		if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
			// Evaluate dynamic method matcher here: static part will already have
			// been evaluated and found to match.
			InterceptorAndDynamicMethodMatcher dm =
					(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
			if (dm.methodMatcher.matches(this.method, this.targetClass, this.arguments)) {
				return dm.interceptor.invoke(this);
			}
			else {
				// Dynamic matching failed.
				// Skip this interceptor and invoke the next in the chain.
				return proceed();
			}
		}
		else {
			// It's an interceptor, so we just invoke it: The pointcut will have
			// 事务拦截器进行调用
			return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
		}
	}

        1.3org.springframework.transaction.interceptor.TransactionInterceptor#invoke(事务拦截器进行调用)

    public Object invoke(final MethodInvocation invocation) throws Throwable {
        // 获取代理对象的目标class
        Class<?> targetClass = invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null;
        
        // 使用事务调用
        return this.invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
            // 从这里触发调用目标方法的
            public Object proceedWithInvocation() throws Throwable {
                return invocation.proceed();
            }
        });
    }

        1.3org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction

        

    protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final TransactionAspectSupport.InvocationCallback invocation) throws Throwable {
        // 通过@EnableTransactionManager 到入了TransactionAttributeSource 可以获取出事务属性对象
        final TransactionAttribute txAttr = this.getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
        // 获取平台的事务管理器
        final PlatformTransactionManager tm = this.determineTransactionManager(txAttr);
        // 获取我们需要切入的方法(也就是我们标识了@Transactional注解的方法)
        final String joinpointIdentification = this.methodIdentification(method, targetClass, txAttr);
        Object result;
    
        // 再这里我们只看我们常用的事务管理器,很明显我们不会配置CallbackPreferringPlatformTransactionManager事务管理器
        if (txAttr != null && tm instanceof CallbackPreferringPlatformTransactionManager) {
            final TransactionAspectSupport.ThrowableHolder throwableHolder = new TransactionAspectSupport.ThrowableHolder();

            try {
                result = ((CallbackPreferringPlatformTransactionManager)tm).execute(txAttr, new TransactionCallback<Object>() {
                    public Object doInTransaction(TransactionStatus status) {
                        TransactionAspectSupport.TransactionInfo txInfo = TransactionAspectSupport.this.prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);

                        Object var4;
                        try {
                            Object var3 = invocation.proceedWithInvocation();
                            return var3;
                        } catch (Throwable var8) {
                            if (txAttr.rollbackOn(var8)) {
                                if (var8 instanceof RuntimeException) {
                                    throw (RuntimeException)var8;
                                }

                                throw new TransactionAspectSupport.ThrowableHolderException(var8);
                            }

                            throwableHolder.throwable = var8;
                            var4 = null;
                        } finally {
                            TransactionAspectSupport.this.cleanupTransactionInfo(txInfo);
                        }

                        return var4;
                    }
                });
                if (throwableHolder.throwable != null) {
                    throw throwableHolder.throwable;
                } else {
                    return result;
                }
            } catch (TransactionAspectSupport.ThrowableHolderException var18) {
                throw var18.getCause();
            } catch (TransactionSystemException var19) {
                if (throwableHolder.throwable != null) {
                    this.logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
                    var19.initApplicationException(throwableHolder.throwable);
                }

                throw var19;
            } catch (Throwable var20) {
                if (throwableHolder.throwable != null) {
                    this.logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
                }

                throw var20;
            }
        } else {
            // 判断有没有必要开启事务
            TransactionAspectSupport.TransactionInfo txInfo = this.createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
            result = null;

            try {
                // 调用我们的目标方法
                result = invocation.proceedWithInvocation();
            } catch (Throwable var16) {
                // 抛出异常进行回顾
                this.completeTransactionAfterThrowing(txInfo, var16);
                throw var16;
            } finally {
                // 清除事务信息
                this.cleanupTransactionInfo(txInfo);
            }
            // 提交事务
            this.commitTransactionAfterReturning(txInfo);
            return result;
        }
    }

1.3.1org.springframework.transaction.interceptor.TransactionAspectSupport#createTransactionIfNecessary

    protected TransactionAspectSupport.TransactionInfo createTransactionIfNecessary(PlatformTransactionManager tm, TransactionAttribute txAttr, final String joinpointIdentification) {
        // 把事务属性包装为
        if (txAttr != null && ((TransactionAttribute)txAttr).getName() == null) {
            txAttr = new DelegatingTransactionAttribute((TransactionAttribute)txAttr) {
                public String getName() {
                    return joinpointIdentification;
                }
            };
        }

        TransactionStatus status = null;
        if (txAttr != null) {
            if (tm != null) {
                // 获取一个事务状态
                status = tm.getTransaction((TransactionDefinition)txAttr);
            } else if (this.logger.isDebugEnabled()) {
                this.logger.debug("Skipping transactional joinpoint [" + joinpointIdentification + "] because no transaction manager has been configured");
            }
        }
        // 准备事务信息
        return this.prepareTransactionInfo(tm, (TransactionAttribute)txAttr, joinpointIdentification, status);
    }

1.3.2org.springframework.transaction.support.AbstractPlatformTransactionManager#getTransaction

    public final TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
        // 1.先去尝试开启一个事务
        Object transaction = this.doGetTransaction();
        boolean debugEnabled = this.logger.isDebugEnabled();
        // 传进来的事务定义为空
        if (definition == null) {
            // 则使用系统默认的
            definition = new DefaultTransactionDefinition();
        }
        
        // 2.判断是否存在事务(若存在事务,在这边直接返回不走下面的处理了)
        if (this.isExistingTransaction(transaction)) {
            return this.handleExistingTransaction((TransactionDefinition)definition, transaction, debugEnabled);
        } else if (((TransactionDefinition)definition).getTimeout() < -1) {
            3:)判读事务超时
            throw new InvalidTimeoutException("Invalid transaction timeout", ((TransactionDefinition)definition).getTimeout());
        } else if (((TransactionDefinition)definition).getPropagationBehavior() == 2) {
            // 不存在事务,需要在这边判断(PROPAGATION_MANDATORY 标识要求当前允许的在事务中,但是第二步进行判断之后
            throw new IllegalTransactionStateException("No existing transaction found for transaction marked with propagation 'mandatory'");
    
        }
         //PROPAGATION_REQUIRED 
        //PROPAGATION_REQUIRES_NEW 
        //PROPAGATION_NESTED
         else if (((TransactionDefinition)definition).getPropagationBehavior() != 0 && ((TransactionDefinition)definition).getPropagationBehavior() != 3 && ((TransactionDefinition)definition).getPropagationBehavior() != 6) {
            if (((TransactionDefinition)definition).getIsolationLevel() != -1 && this.logger.isWarnEnabled()) {
                this.logger.warn("Custom isolation level specified but no actual transaction initiated; isolation level will effectively be ignored: " + definition);
            }
            //创建一个空的事物.
            boolean newSynchronization = this.getTransactionSynchronization() == 0;
            return this.prepareTransactionStatus((TransactionDefinition)definition, (Object)null, true, newSynchronization, debugEnabled, (Object)null);
        } else {
            //挂起当前事务,但是当前是没有事务的
            AbstractPlatformTransactionManager.SuspendedResourcesHolder suspendedResources = this.suspend((Object)null);
            if (debugEnabled) {
                this.logger.debug("Creating new transaction with name [" + ((TransactionDefinition)definition).getName() + "]: " + definition);
            }

            try {
                boolean newSynchronization = this.getTransactionSynchronization() != 2;
                //创建一个新的事物状态
                DefaultTransactionStatus status = this.newTransactionStatus((TransactionDefinition)definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
                // //开启一个事物
                this.doBegin(transaction, (TransactionDefinition)definition);
                // //准备事物同步
                this.prepareSynchronization(status, (TransactionDefinition)definition);
                return status;
            } catch (RuntimeException var7) {
                this.resume((Object)null, suspendedResources);
                throw var7;
            } catch (Error var8) {
                this.resume((Object)null, suspendedResources);
                throw var8;
            }
        }
    }



===============================================代码1处中的代码=================
    protected Object doGetTransaction() {
        //创建一个数据库事务管理器
        DataSourceTransactionManager.DataSourceTransactionObject txObject = new DataSourceTransactionManager.DataSourceTransactionObject();
        //设置一个事务保存点
        txObject.setSavepointAllowed(this.isNestedTransactionAllowed());
        //从事务同步管理器中获取连接持有器
        ConnectionHolder conHolder = (ConnectionHolder)TransactionSynchronizationManager.getResource(this.dataSource);
        //把持有器设置到对象中
        txObject.setConnectionHolder(conHolder, false);
        //返回一个事务对象
        return txObject;
    }

    //第一次进来不会走这个逻辑
    protected boolean isExistingTransaction(Object transaction) {
        //获取事务对象中的持有器
        DataSourceTransactionManager.DataSourceTransactionObject txObject = (DataSourceTransactionManager.DataSourceTransactionObject)transaction;
        //持有器不为空且 有事务激活
        return txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive();
    }


=====================handleExistingTransaction===============================


    // 第一次调用的时候
    protected void doBegin(Object transaction, TransactionDefinition definition) {
        DataSourceTransactionManager.DataSourceTransactionObject txObject = (DataSourceTransactionManager.DataSourceTransactionObject)transaction;
        Connection con = null;

        try {
            //第一次进来,事务持有器中是没有对象的,所以我们需要自己手动的设置进去
            if (!txObject.hasConnectionHolder() || txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
                //获取一个数据库连接
                Connection newCon = this.dataSource.getConnection();
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
                }
                //把数据库连接封装为一个持有器对象并且设置到事务对象中
                txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
            }
            //开始同步标志
            txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
            con = txObject.getConnectionHolder().getConnection();
            //获取事务的隔离级别
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);

            // 关闭事务自动提交
            if (con.getAutoCommit()) {
                txObject.setMustRestoreAutoCommit(true);
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
                }

                con.setAutoCommit(false);
            }
            
            判断事务是不是为只读的事务
            this.prepareTransactionalConnection(con, definition);
            //设置事务激活
            txObject.getConnectionHolder().setTransactionActive(true);
            int timeout = this.determineTimeout(definition);
            if (timeout != -1) {
                txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
            }
            
            //把数据源和事务持有器保存到事务同步管理器中
            if (txObject.isNewConnectionHolder()) {
                TransactionSynchronizationManager.bindResource(this.getDataSource(), txObject.getConnectionHolder());
            }

        } catch (Throwable var7) {
            if (txObject.isNewConnectionHolder()) {
                DataSourceUtils.releaseConnection(con, this.dataSource);
                txObject.setConnectionHolder((ConnectionHolder)null, false);
            }

            throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", var7);
        }
    }



========================== prepareSynchronization(status, definition);把当前的事务设置到同步管理器中====
    protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) {
        if (status.isNewSynchronization()) {
              设置事务激活  TransactionSynchronizationManager.setActualTransactionActive(status.hasTransaction());
            //设置隔离级别
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(definition.getIsolationLevel() != -1 ? definition.getIsolationLevel() : null);
            //设置只读事务
TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly());
            
            // 设置事务的名称
TransactionSynchronizationManager.setCurrentTransactionName(definition.getName());
            TransactionSynchronizationManager.initSynchronization();
        }

    }

        到这里有关spring事务源码代理对象的调用流程就已经说完了,整体下来还是比较模糊,这里大家需要多调试,debug去跟源码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值