Spring源码学习19

1.TransactionInterceptor;该类实现了MethodInterceptor,所以事务的增强逻辑最终会在TransactionInterceptor.invoke()方法

@Override
	public Object invoke(final MethodInvocation invocation) throws Throwable {
		// Work out the target class: may be {@code null}.
		// The TransactionAttributeSource should be passed the target class
		// as well as the method, which may be from an interface.
		// 计算出目标类
		// TransactionAttributeSource应该传递给目标类
		// 以及可以来自Interface的方法。

		// 得到目标类
		Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

		// Adapt to TransactionAspectSupport's invokeWithinTransaction...
		//适配TransactionAspectSupport的invokeWithinTransaction
		return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() {
			//执行目标方法
			@Override
			public Object proceedWithInvocation() throws Throwable {
				return invocation.proceed();
			}
		});
	}

最终实现委托到了父类TransactionAspectSupport.invokeWithinTransaction

2.TransactionAspectSupport.invokeWithinTransaction

/**
	 * 基于arround-advice的基础委托方法,委托个这个类的其他模板方法.
	 * 能够处理{@link CallbackPreferringPlatformTransactionManager}
	 * 以及常规{@link PlatformTransactionManager}实现。
	 *
	 * @param method the Method being invoked
	 * @param targetClass the target class that we're invoking the method on
	 * @param invocation the callback to use for proceeding with the target invocation
	 * @return the return value of the method, if any
	 * @throws Throwable propagated from the target invocation
	 */
	protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final InvocationCallback invocation)
			throws Throwable {

		// 获取事务的属性
		final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
		// 确定事务管理器
		final PlatformTransactionManager tm = determineTransactionManager(txAttr);
		// 构造方法唯一标识如:org.springframework.study.day16.service.TbTestService.save;
		final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
		// 我debug了下使用tx:advice和@Transaction注解的事务 会经过该方法!
		if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
			// Standard transaction demarcation with getTransaction and commit/rollback calls.

			// 使用事务管理器tm创建TransactionInfo
			TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);

			Object retVal;
			try {
				// This is an around advice: Invoke the next interceptor in the chain.
				// This will normally result in a target object being invoked.

				// 这是一个环绕增强:所以在这里调用拦截器链中的下一个interceptor
				// 这通常会导致调用目标对象。
				retVal = invocation.proceedWithInvocation();
			}
			catch (Throwable ex) {
				// target invocation exception
				// 目标方法调用异常
				completeTransactionAfterThrowing(txInfo, ex);
				throw ex;
			}
			finally {
				//清楚事务信息
				cleanupTransactionInfo(txInfo);
			}
			//提交事务
			commitTransactionAfterReturning(txInfo);
			return retVal;
		}

		else {
			final ThrowableHolder throwableHolder = new ThrowableHolder();

			// 它是一个CallbackPreferringPlatformTransactionManager:传递一个TransactionCallback。
			try {

				Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr,
						new TransactionCallback<Object>() {
							@Override
							public Object doInTransaction(TransactionStatus status) {
								TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
								try {
									return invocation.proceedWithInvocation();
								}
								catch (Throwable ex) {
									if (txAttr.rollbackOn(ex)) {
										// A RuntimeException: will lead to a rollback.
										if (ex instanceof RuntimeException) {
											throw (RuntimeException) ex;
										}
										else {
											throw new ThrowableHolderException(ex);
										}
									}
									else {
										// A normal return value: will lead to a commit.
										throwableHolder.throwable = ex;
										return null;
									}
								}
								finally {
									cleanupTransactionInfo(txInfo);
								}
							}
						});

				// Check result state: It might indicate a Throwable to rethrow.
				if (throwableHolder.throwable != null) {
					throw throwableHolder.throwable;
				}
				return result;
			}
			catch (ThrowableHolderException ex) {
				throw ex.getCause();
			}
			catch (TransactionSystemException ex2) {
				if (throwableHolder.throwable != null) {
					logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
					ex2.initApplicationException(throwableHolder.throwable);
				}
				throw ex2;
			}
			catch (Throwable ex2) {
				if (throwableHolder.throwable != null) {
					logger.error("Application exception overridden by commit exception", throwableHolder.throwable);
				}
				throw ex2;
			}
		}
	}
  • a.getTransactionAttributeSource().getTransactionAttribute(method, targetClass);我们可以通过tx:advice标签元素或者@Transaction实现事务;他们各自的TransactionAttritebuteSource类型分别是:NameMatchTransactionAttributeSource、AnnotationTransactionAttributeSources所以获取TransactionAttribute属性的方式有所不同;
  • @Override
    	public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
    		if (!ClassUtils.isUserLevelMethod(method)) {
    			return null;
    		}
    
    		// Look for direct name match.
    		String methodName = method.getName();
    		// 根据名称
    		TransactionAttribute attr = this.nameMap.get(methodName);
    
    		if (attr == null) {
    			// Look for most specific name match.
    			//寻找最具体的名称匹配。
    			String bestNameMatch = null;
    			for (String mappedName : this.nameMap.keySet()) {
    				if (isMatch(methodName, mappedName) &&
    						(bestNameMatch == null || bestNameMatch.length() <= mappedName.length())) {
    					attr = this.nameMap.get(mappedName);
    					bestNameMatch = mappedName;
    				}
    			}
    		}
    		return attr;
    	}
    
    
       /**
    	 * 确定此方法调用的事务属性
    	 * <p>如果未找到方法属性,则默认为类的事务属性.
    	 * @param method the method for the current invocation (never {@code null})
    	 * @param targetClass the target class for this invocation (may be {@code null})
    	 * @return a TransactionAttribute for this method, or {@code null} if the method
    	 * is not transactional
    	 */
    	@Override
    	public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
    		//object的method方法比如(equals clone等等),直接返回Null
    		if (method.getDeclaringClass() == Object.class) {
    			return null;
    		}
    
    		// First, see if we have a cached value.
    		// 我们先从缓存看看有没有
    		// MethodClassKey
    		Object cacheKey = getCacheKey(method, targetClass);
    		//缓存的TransactionAtrribute
    		TransactionAttribute cached = this.attributeCache.get(cacheKey);
    		//缓存存在
    		if (cached != null) {
    			// Value will either be canonical value indicating there is no transaction attribute,
    			// or an actual transaction attribute.
    			//值将是规范值,表示没有事务属性或实际事务属性。返回null
    			if (cached == NULL_TRANSACTION_ATTRIBUTE) {
    				return null;
    			}
    			else {
    				//返回缓存的TransactionAttribute
    				return cached;
    			}
    		}
    		else {
    			// We need to work it out.
    			// 获取txAttr属性好伐!
    			TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
    			// 为null 放一个NULL_TRANSACTION_ATTRIBUTE
    			if (txAttr == null) {
    				this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
    			}
    			else {
    				//如果该targetClass的method方法有TransactionAttribute属性
    				//设置descriptor属性,不是我们关注的重点
    				String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
    				if (txAttr instanceof DefaultTransactionAttribute) {
    					((DefaultTransactionAttribute) txAttr).setDescriptor(methodIdentification);
    				}
    				if (logger.isDebugEnabled()) {
    					logger.debug("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
    				}
    				//放入缓存
    				this.attributeCache.put(cacheKey, txAttr);
    			}
    			return txAttr;
    		}
    	}
  • b.获取事务 管理器determineTransactionManager(txAttr);事务管理器的优先级:通过qualifier属性>TransactionAspectSupport.transactionManagerBeanName属性配置>TransactionAspectSupport.transactionManager属性配置>xml配置
  • /**
    	 * 确定要用于给定事务的特定事务管理器。
    	 */
    	protected PlatformTransactionManager determineTransactionManager(TransactionAttribute txAttr) {
    		// Do not attempt to lookup tx manager if no tx attributes are set
    		// txAttr==null或者beanFactory==null直接获取本来的transactionManager
    		if (txAttr == null || this.beanFactory == null) {
    			return getTransactionManager();
    		}
    
    		String qualifier = txAttr.getQualifier();
    		//如果定义了qualifier属性根据qualifier选择不同的事务管理器
    		if (StringUtils.hasText(qualifier)) {
    			return determineQualifiedTransactionManager(qualifier);
    		}
    		//如果给定了transactionManagerBeanName;从beanFactory中获取
    		else if (StringUtils.hasText(this.transactionManagerBeanName)) {
    			return determineQualifiedTransactionManager(this.transactionManagerBeanName);
    		}
    		else {
    			//直接获取当前类的transactionManager
    			PlatformTransactionManager defaultTransactionManager = getTransactionManager();
    			if (defaultTransactionManager == null) {
    				//当前类也没有定义哎嘿嘿,那就从beanFactory中获取一个类型为PlatformTransactionManager的
    				//放入到缓存里谢谢
    				defaultTransactionManager = this.transactionManagerCache.get(DEFAULT_TRANSACTION_MANAGER_KEY);
    				if (defaultTransactionManager == null) {
    					defaultTransactionManager = this.beanFactory.getBean(PlatformTransactionManager.class);
    					this.transactionManagerCache.putIfAbsent(
    							DEFAULT_TRANSACTION_MANAGER_KEY, defaultTransactionManager);
    				}
    			}
    			return defaultTransactionManager;
    		}
    	}
    
    	private PlatformTransactionManager determineQualifiedTransactionManager(String qualifier) {
    		PlatformTransactionManager txManager = this.transactionManagerCache.get(qualifier);
    		if (txManager == null) {
    			txManager = BeanFactoryAnnotationUtils.qualifiedBeanOfType(
    					this.beanFactory, PlatformTransactionManager.class, qualifier);
    			this.transactionManagerCache.putIfAbsent(qualifier, txManager);
    		}
    		return txManager;
    	}
  • c.使用事务管理器tm创建TransactionInfo对象createTransactionIfNecessary(tm, txAttr, joinpointIdentification);该方法的分析是事务实现关键,单独开篇福分析。
  • /**
    	 * 必要时根据给定的TransactionAttribute创建事务。
    	 * 允许调用者通过TransactionAttributeSource执行自定义TransactionAttribute查找。
    	 * @param txAttr the TransactionAttribute (may be {@code null})
    	 * @param joinpointIdentification the fully qualified method name
    	 * (used for monitoring and logging purposes)
    	 * @return a TransactionInfo object, whether or not a transaction was created.
    	 * The {@code hasTransaction()} method on TransactionInfo can be used to
    	 * tell if there was a transaction created.
    	 * @see #getTransactionAttributeSource()
    	 */
    	@SuppressWarnings("serial")
    	protected TransactionInfo createTransactionIfNecessary(
    			PlatformTransactionManager tm, TransactionAttribute txAttr, final String joinpointIdentification) {
    
    		if (txAttr != null && txAttr.getName() == null) {
    			//如果没有指定名称,封装txAttr为DelegatingTransactionAttribute并使用joinpointIdentification
    			//作为对象名称
    			txAttr = new DelegatingTransactionAttribute(txAttr) {
    				@Override
    				public String getName() {
    					return joinpointIdentification;
    				}
    			};
    		}
    		//事务状态;如果配置了txAttr;则使用txAttr创建事务status
    		TransactionStatus status = null;
    		if (txAttr != null) {
    			if (tm != null) {
    				//获取transactionStatus
    				status = tm.getTransaction(txAttr);
    			}
    			else {
    				if (logger.isDebugEnabled()) {
    					logger.debug("Skipping transactional joinpoint [" + joinpointIdentification +
    							"] because no transaction manager has been configured");
    				}
    			}
    		}
    		//生成一个transactionInfo
    		return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
    	}
  • d.调用目标对象方法retVal = invocation.proceedWithInvocation();
  • @Override
    			public Object proceedWithInvocation() throws Throwable {
    				return invocation.proceed();
    			}
  • e.目标方法调用一场的回滚处理completeTransactionAfterThrowing(txInfo, ex);后面分析
  • f.清楚事务信息:cleanupTransactionInfo(txInfo);后面分析
  • g.提交事务commitTransactionAfterReturning(txInfo);后面分析
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值