• Spring之事务实现原理及其注解@Transactional底层和传播机制原理


    系列文章目录

    第一章 Spring之AOP-JDK动态代理源码解析
    第二章 Spring之事务实现原理及其注解@Transactional底层和传播机制原理



    前言

    本文介绍Spring之事务实现原理,以及注解@Transactional底层实现和7种传播传播机制原理


    一、@EnableTransactionManagement入口

    Spring支持事务功能的入口注解,通过@Import注解向Spring容器导入TransactionManagementConfigurationSelector组件,该注解实现了ImportSelector接口(扩展点)

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    //@Import注解可以为我们容器中导入组件
    @Import(TransactionManagementConfigurationSelector.class)
    public @interface EnableTransactionManagement {
    
    	//默认为false
    	boolean proxyTargetClass() default false;
    
    	//默认为AdviceMode.PROXY
    	AdviceMode mode() default AdviceMode.PROXY;
    
    	int order() default Ordered.LOWEST_PRECEDENCE;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    注:@EnableTransactionManagement和@EnableAspectJAutoProxy需要一起在配置类中被使用,事务是借组AOP切面来进行实现。

    二、TransactionManagementConfigurationSelector组件

    2.1.selectImports扩展点方法

    导入两个组件:AutoProxyRegistrar和ProxyTransactionManagementConfiguration
    当在Spring容器中加载bean定义的时候会回调我们的selectImports方法,方法的返回值是我们需要导入类的全类名路径,然后这个类就会被加载到容器中

    @Override
    	protected String[] selectImports(AdviceMode adviceMode) {
    		switch (adviceMode) {
    			/**
    			 * 容器中导入二个组件
    			 * 一个是AutoProxyRegistrar
    			 * 一个是ProxyTransactionManagementConfiguration
    			 */
    			case PROXY:
    				return new String[] {AutoProxyRegistrar.class.getName(),
    						ProxyTransactionManagementConfiguration.class.getName()};
    			case ASPECTJ:
    				return new String[] {
    						TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME};
    			default:
    				return null;
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2.2 组件1-AutoProxyRegistrar

    该组件实现了ImportBeanDefinitionRegistrar接口,也是为一个扩展点,核心是向Spring容器注册一个BeanDefinition

    public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
    
    	private final Log logger = LogFactory.getLog(getClass());
    
    	@Override
    	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    		boolean candidateFound = false;
    		//获取导入类的注解元数据信息
    		Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
    		for (String annType : annTypes) {
    			AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
    			if (candidate == null) {
    				continue;
    			}
    			//获取mode属性
    			Object mode = candidate.get("mode");
    			//获取proxyTargetClass属性
    			Object proxyTargetClass = candidate.get("proxyTargetClass");
    			if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
    					Boolean.class == proxyTargetClass.getClass()) {
    				candidateFound = true;
    				if (mode == AdviceMode.PROXY) {
    					//注册Bean定义
    					AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
    					if ((Boolean) proxyTargetClass) {
    						//修改bean定义,设置proxyTargetClass为True
    						AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
    						return;
    					}
    				}
    			}
    		}
    		if (!candidateFound && logger.isWarnEnabled()) {
    			String name = getClass().getSimpleName();
    			logger.warn(String.format("%s was imported but no annotations were found " +
    					"having both 'mode' and 'proxyTargetClass' attributes of type " +
    					"AdviceMode and boolean respectively. This means that auto proxy " +
    					"creator registration and configuration may not have occurred as " +
    					"intended, and components may not be proxied as expected. Check to " +
    					"ensure that %s has been @Import'ed on the same class where these " +
    					"annotations are declared; otherwise remove the import of %s " +
    					"altogether.", name, name, name));
    		}
    	}
    
    }
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46

    注册的Bean定义为InfrastructureAdvisorAutoProxyCreator

    public static BeanDefinition registerAutoProxyCreatorIfNecessary(
    			BeanDefinitionRegistry registry, @Nullable Object source) {
    		return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
    	}
    
    • 1
    • 2
    • 3
    • 4

    2.2.1 InfrastructureAdvisorAutoProxyCreator

    该类重写了筛选合格的advisor方法,当Spring容器中包含的bean定义的角色类型为BeanDefinition.ROLE_INFRASTRUCTURE时,即为合格的Advisor

    public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
    
    	@Nullable
    	private ConfigurableListableBeanFactory beanFactory;
    
    
    	@Override
    	protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    		super.initBeanFactory(beanFactory);
    		this.beanFactory = beanFactory;
    	}
    
    	/**
    	 * 判断事务注解导入的BeanFactoryTransactionAttributeSourceAdvisor是不是我们想要的Advisor
    	 */
    	@Override
    	protected boolean isEligibleAdvisorBean(String beanName) {
    		/**
    		 * 1.容器中包含了这个bean定义,
    		 * 2.并且bean定义的角色BeanDefinition.ROLE_INFRASTRUCTURE
    		 * 这几个条件符合即是我们想要查找的advisor
    		 */
    		return (this.beanFactory != null && this.beanFactory.containsBeanDefinition(beanName) &&
    				this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
    	}
    
    }
    
    • 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

    2.3 组件2-ProxyTransactionManagementConfiguration

    注册启用基于代理的注解驱动的事务管理所需的Spring基础设施 bean。
    包含三个bean,一个Advisor增强器,一个Advice通知,一个TransactionAttributeSource事务属性源

    @Configuration
    public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
    
    	/**
    	 * 导入了Advisor接口的实现类BeanFactoryTransactionAttributeSourceAdvisor-关于事务的切面信息
    	 * @return
    	 */
    	@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
    	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    	public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
    		BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
    		advisor.setTransactionAttributeSource(transactionAttributeSource());
    		//添加定义的Advice通知
    		advisor.setAdvice(transactionInterceptor());
    		if (this.enableTx != null) {
    			advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
    		}
    		return advisor;
    	}
    
    	/**
    	 * 事务属性源对象-用于获取事务属性对象
    	 * 初始化事务注解解析器:SpringTransactionAnnotationParser
    	 * @return
    	 */
    	@Bean
    	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    	public TransactionAttributeSource transactionAttributeSource() {
    		return new AnnotationTransactionAttributeSource();
    	}
    
    	/**
    	 * 用户拦截事务方法执行的,一个Advice通知
    	 * @return
    	 */
    	@Bean
    	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    	public TransactionInterceptor transactionInterceptor() {
    		TransactionInterceptor interceptor = new TransactionInterceptor();
    		interceptor.setTransactionAttributeSource(transactionAttributeSource());
    		if (this.txManager != null) {
    			interceptor.setTransactionManager(this.txManager);
    		}
    		return interceptor;
    	}
    
    }
    
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    2.3.1 PointcutAdvisor接口实现类

    BeanFactoryTransactionAttributeSourceAdvisor实现类,当AOP匹配到了当前的Adivisor之后,会去创建动态代理,当动态代理对象执行被代理对象的方法时,如果为JDK动态代理会进入invoke方法执行代理逻辑,在代理逻辑中执行获取匹配的advice通知责任链时,会去调用每个匹配的advisor的getPointcut方法,去进行切点匹配

    public class BeanFactoryTransactionAttributeSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
    
    	@Nullable
    	private TransactionAttributeSource transactionAttributeSource;
    
    	/**
    	 * 事务属性源切点
    	 */
    	private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
    		@Override
    		@Nullable
    		protected TransactionAttributeSource getTransactionAttributeSource() {
    			return transactionAttributeSource;
    		}
    	};
    
    
    	/**
    	 * Set the transaction attribute source which is used to find transaction
    	 * attributes. This should usually be identical to the source reference
    	 * set on the transaction interceptor itself.
    	 * @see TransactionInterceptor#setTransactionAttributeSource
    	 */
    	public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) {
    		this.transactionAttributeSource = transactionAttributeSource;
    	}
    
    	/**
    	 * Set the {@link ClassFilter} to use for this pointcut.
    	 * Default is {@link ClassFilter#TRUE}.
    	 */
    	public void setClassFilter(ClassFilter classFilter) {
    		this.pointcut.setClassFilter(classFilter);
    	}
    
    	//重写了getPointCut方法,执行事务代理逻辑的时候会获取切点进行匹配
    	@Override
    	public Pointcut getPointcut() {
    		return this.pointcut;
    	}
    
    }
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42

    2.3.2 TransactionAttributeSourcePointcut 切点类

    主要是一个MethodMatcher接口提供的方法匹配方法

    abstract class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
    	
    	//放置了ClassFilter,用于过滤当前类或者方法是否有注解@Transactionl
    	//最终会进入SpringTransactionAnnotationParser方法
    	protected TransactionAttributeSourcePointcut() {
    		setClassFilter(new TransactionAttributeSourceClassFilter());
    	}
    
    	@Override
    	public boolean matches(Method method, @Nullable Class<?> targetClass) {
    		if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
    			return false;
    		}
    		/**
    		 * 获取@EnableTransactionManagement注解为Spring容器中导入的ProxyTransactionManagementConfiguration
             * 配置类中的TransactionAttributeSource事务注解属性对象
    		 */
    		TransactionAttributeSource tas = getTransactionAttributeSource();
    		// 通过getTransactionAttribute看方法或者类是否有@Transactional注解,tas为AnnotationTransactionAttributeSource实例,调用getTransactionAttribute会调用父类AbstractFallbackTransactionAttributeSource中的方法
    		return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
    	}
    
    	@Override
    	public boolean equals(Object other) {
    		if (this == other) {
    			return true;
    		}
    		if (!(other instanceof TransactionAttributeSourcePointcut)) {
    			return false;
    		}
    		TransactionAttributeSourcePointcut otherPc = (TransactionAttributeSourcePointcut) other;
    		return ObjectUtils.nullSafeEquals(getTransactionAttributeSource(), otherPc.getTransactionAttributeSource());
    	}
    
    	@Override
    	public int hashCode() {
    		return TransactionAttributeSourcePointcut.class.hashCode();
    	}
    
    	@Override
    	public String toString() {
    		return getClass().getName() + ": " + getTransactionAttributeSource();
    	}
    
    
    	/**
    	 * Obtain the underlying TransactionAttributeSource (may be {@code null}).
    	 * To be implemented by subclasses.
    	 */
    	@Nullable
    	protected abstract TransactionAttributeSource getTransactionAttributeSource();
    
    }
    
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    AbstractFallbackTransactionAttributeSource#getTransactionAttribute判断方法或者类是否有@Transactional注解,也就是解析@Transactional注解和方法的描述符,并把TransactionAttribute放入缓存

    	public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
    		//判断method所在的class 是不是Object类型
    		if (method.getDeclaringClass() == Object.class) {
    			return null;
    		}
    
    		//构建缓存key
    		Object cacheKey = getCacheKey(method, targetClass);
    		//先去缓存中获取
    		TransactionAttribute cached = this.attributeCache.get(cacheKey);
    		//缓存中不为空
    		if (cached != null) {
    			//判断缓存中的对象是不是空事务属性的对象
    			if (cached == NULL_TRANSACTION_ATTRIBUTE) {
    				return null;
    			}
    			//不是的话 就进行返回
    			else {
    				return cached;
    			}
    		}
    		else {
    			//查找事务注解
    			TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
    			// 若解析出来的事务注解属性为空
    			if (txAttr == null) {
    				//往缓存中存放空事务注解属性
    				this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
    			}
    			else {
    				//执行方法的描述符 全类名+方法名
    				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;
    		}
    	}
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    三、TransactionInterceptor事务方法过滤

    通过上面的源码分析可知,当开启AOP和事务及方法或者类上面存在@Transactional注解会进入该类的方法执行过滤逻辑,即TransactionInterceptor#invoke方法。(AOP的Advice责任链模式执行)

    	public Object invoke(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.
    		Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
    
    		// 执行事务逻辑
    		return invokeWithinTransaction(invocation.getMethod(), targetClass, new CoroutinesInvocationCallback() {
    			@Override
    			@Nullable
    			public Object proceedWithInvocation() throws Throwable {
    				return invocation.proceed();
    			}
    			@Override
    			public Object getTarget() {
    				return invocation.getThis();
    			}
    			@Override
    			public Object[] getArguments() {
    				return invocation.getArguments();
    			}
    		});
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    3.1 invokeWithinTransaction方法

    	protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
    			final InvocationCallback invocation) throws Throwable {
    
    		//获取事务属性源对象,在配置类中添加的
    		TransactionAttributeSource tas = getTransactionAttributeSource();
    		//txAttr获取到的内容是从解析后的缓存中获取
    		// 1.获取解析后的事务属性信息
    		final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
    		// 获取配置的事务管理器对象
    		final PlatformTransactionManager tm = determineTransactionManager(txAttr);
    		// 2.从tx属性对象中获取出标注了@Transactionl的方法描述符
    		final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
    
    		//处理声明式事务
    		if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
    			//**************核心,有没有必要创建事务*************
    			TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
    
    			Object retVal;
    			try {
    				//回调目标方法
    				retVal = invocation.proceedWithInvocation();
    			}
    			catch (Throwable ex) {
    				//抛出异常进行回滚处理
    				completeTransactionAfterThrowing(txInfo, ex);
    				throw ex;
    			}
    			finally {
    				//清空我们的线程变量中transactionInfo的值
    				cleanupTransactionInfo(txInfo);
    			}
    			//提交事务
    			commitTransactionAfterReturning(txInfo);
    			return retVal;
    		}
    		// 编程式事务:(回调偏向)
    		else {
    			final ThrowableHolder throwableHolder = new ThrowableHolder();
    
    			// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
    			try {
    				Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, 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;
    			}
    		}
    	}
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92

    3.2 determineTransactionManager推断事务管理器对象

    @Nullable
    	protected PlatformTransactionManager determineTransactionManager(@Nullable TransactionAttribute txAttr) {
    		// Do not attempt to lookup tx manager if no tx attributes are set
    		if (txAttr == null || this.beanFactory == null) {
    			return getTransactionManager();
    		}
    		//通过@Transactionnal("xxx")指定事务管理器
    		String qualifier = txAttr.getQualifier(); 
    		if (StringUtils.hasText(qualifier)) {
    			return determineQualifiedTransactionManager(this.beanFactory, qualifier);
    		}
    		else if (StringUtils.hasText(this.transactionManagerBeanName)) {
    			return determineQualifiedTransactionManager(this.beanFactory, this.transactionManagerBeanName);
    		}
    		else {
    			//配置类中配置的默认的事务管理器
    			PlatformTransactionManager defaultTransactionManager = getTransactionManager();
    			if (defaultTransactionManager == null) {
    				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;
    		}
    	}
    
    • 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

    3.3 methodIdentification获取描述符

    AbstractFallbackTransactionAttributeSource#getTransactionAttribute方法也调用过,此次会从缓存中获取TransactionAttribute

    private String methodIdentification(Method method, @Nullable Class<?> targetClass,
    			@Nullable TransactionAttribute txAttr) {
    
    		//全类名+方法名
    		String methodIdentification = methodIdentification(method, targetClass);
    		if (methodIdentification == null) {
    			if (txAttr instanceof DefaultTransactionAttribute) {
    				methodIdentification = ((DefaultTransactionAttribute) txAttr).getDescriptor();
    			}
    			if (methodIdentification == null) {
    				methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
    			}
    		}
    		return methodIdentification;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    3.4 createTransactionIfNecessary是否有必要创建事务

    protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
    			@Nullable TransactionAttribute txAttr, final String joinpointIdentification) {
    
    		// 如果还没有定义名字,把连接点的ID定义成事务的名称
    		if (txAttr != null && txAttr.getName() == null) {
    			txAttr = new DelegatingTransactionAttribute(txAttr) {
    				@Override
    				public String getName() {
    					return joinpointIdentification;
    				}
    			};
    		}
    
    		TransactionStatus status = null;
    		//当txAttr和tm都不等于空的时候,去通过事务管理器tm获取事务
    		if (txAttr != null) {
    			if (tm != null) {
    				//获取一个事务状态
    				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);
    	}
    
    • 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

    3.5 AbstractPlatformTransactionManager#getTransaction获取事务

    	@Override
    	public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
    		//尝试获取一个事务对象
    		Object transaction = doGetTransaction();
    
    		// Cache debug flag to avoid repeated checks.
    		boolean debugEnabled = logger.isDebugEnabled();
    
    		/**
    		 * 判断从上一个方法传递进来的事务属性是不是为空
    		 */
    		if (definition == null) {
    
    			definition = new DefaultTransactionDefinition();
    		}
    
    		/**
    		 * 判断是不是已经存在了事务对象(事务嵌套)
    		 */
    		if (isExistingTransaction(transaction)) {
    			//处理存在的事务
    			return handleExistingTransaction(definition, transaction, debugEnabled);
    		}
    
    		//检查事务设置的超时时间
    		if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
    			throw new InvalidTimeoutException("Invalid transaction timeout", definition.getTimeout());
    		}
    
    		/**
    		 * 由于isExistingTransaction(transaction)跳过了这里,说明当前是不存在事务的
    		 * 1.PROPAGATION_MANDATORY传播机制,表示必须运行在事务中,若当前没有事务就抛出异常,那么就会抛出异常
    		 */
    		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
    			throw new IllegalTransactionStateException(
    					"No existing transaction found for transaction marked with propagation 'mandatory'");
    		}
    		/**
    		 * 2.PROPAGATION_REQUIRED 当前存在事务就加入到当前的事务,没有就新开一个
    		 * 3.PROPAGATION_REQUIRES_NEW:新开一个事务,若当前存在事务就挂起当前事务
    		 * 4.PROPAGATION_NESTED: 
    		    表示如果当前正有一个事务在运行中,则该方法应该运行在 一个嵌套的事务中,
    		    被嵌套的事务可以独立于封装事务进行提交或者回滚(保存点),
    		    如果封装事务不存在,行为就像 PROPAGATION_REQUIRES NEW
    		 */
    else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
    				def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
    				def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
    			/**
    			 * 挂起当前事务,在这里为啥传入null?
    			 * 因为逻辑走到这里了,经过了上面的isExistingTransaction(transaction) 判断当前是不存在事务的
    			 * 所有再这里是挂起当前事务传递一个null进去
    			 */
    			SuspendedResourcesHolder suspendedResources = suspend(null);
    			if (debugEnabled) {
    				logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
    			}
    			try {
    				//开启事务
    				return startTransaction(def, transaction, debugEnabled, suspendedResources);
    			}
    			catch (RuntimeException | Error ex) {
    				resume(null, suspendedResources);
    				throw ex;
    			}
    		}
    		else {
    			// Create "empty" transaction: no actual transaction, but potentially synchronization.
    			if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
    				logger.warn("Custom isolation level specified but no actual transaction initiated; " +
    						"isolation level will effectively be ignored: " + def);
    			}
    			boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
    			return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
    		}
    	}
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76

    3.5.1 第一种情况-事务一开始不存在

    在UserService的test方法添加了@Transactional注解

    @Component
    public class UserService {
    
    	@Autowired
    	private JdbcTemplate jdbcTemplate;
    
    	@Autowired
    	private UserService userService;
    
    	public UserService() {
    		System.out.println("UserService created");
    	}
    
    	@Transactional
    	public void test(){
    		jdbcTemplate.execute("insert into student values(2,'1')");
    		userService.b();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    使用AnnotationConfigApplicationContext去获取Bean并调用test方法

    public class MainClass {
    
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
    		UserService userService = (UserService) context.getBean("userService");
    		userService.test();
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    以上的这种情况,一开始就是不存在事务,该isExistingTransaction(transaction) 判断不通过
    doGetTransaction方法获取事务

    protected Object doGetTransaction() {
    		//创建一个数据源事务对象
    		DataSourceTransactionObject txObject = new DataSourceTransactionObject();
    		//是否允许当前事务设置保持点
    		txObject.setSavepointAllowed(isNestedTransactionAllowed());
    		/**
    		 * TransactionSynchronizationManager事务同步管理器对象(该类中都是局部线程变量,ThreadLocal实现)
    		 * 用来保存当前事务的信息,我们第一次从这里去线程变量中获取 事务连接持有器对象 通过数据源为key去获取
    		 * 第一次进来开始事务 我们的事务同步管理器中没有被存放.所以此时获取出来的conHolder为null
    		 */
    		ConnectionHolder conHolder =
    				(ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource());
    		//false代表不是新开
    		txObject.setConnectionHolder(conHolder, false);
    		//返回事务对象
    		return txObject;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    startTransaction开启事务方法

    private TransactionStatus startTransaction(TransactionDefinition definition, Object transaction,
    			boolean debugEnabled, @Nullable SuspendedResourcesHolder suspendedResources) {
    
    		boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
    		//这其中的true代表为新开事务
    		DefaultTransactionStatus status = newTransactionStatus(
    				definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
    		//
    		doBegin(transaction, definition);
    		prepareSynchronization(status, definition);
    		return status;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    doBegin方法获取数据库连接,创建ConnectionHolder放入事务对象,并设置为新建ConnectionHolder标识true

    	protected void doBegin(Object transaction, TransactionDefinition definition) {
    		DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
    		Connection con = null;
    
    		try {
    			//一开始进入为null
    			if (!txObject.hasConnectionHolder() ||
    					txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
    				//获取连接
    				Connection newCon = obtainDataSource().getConnection();
    				if (logger.isDebugEnabled()) {
    					logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
    				}
    				//创建ConnectionHolder,设置为新建标识,放入事务对象中
    				txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
    			}
    			//将资源标记为与事务同步
    			txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
    			//从事务中拿出数据库连接
    			con = txObject.getConnectionHolder().getConnection();
    
    			Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
    			//设置事务隔离级别
    			txObject.setPreviousIsolationLevel(previousIsolationLevel);
    			txObject.setReadOnly(definition.isReadOnly());
    
    			// Switch to manual commit if necessary. This is very expensive in some JDBC drivers,
    			// so we don't want to do it unnecessarily (for example if we've explicitly
    			// configured the connection pool to set it already).
    			//设置AutoCommit为false,手动提交
    			if (con.getAutoCommit()) {
    				txObject.setMustRestoreAutoCommit(true);
    				if (logger.isDebugEnabled()) {
    					logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
    				}
    				con.setAutoCommit(false);
    			}
    			//如果isReadOnly为true,就是执行的stmt.executeUpdate("SET TRANSACTION READ ONLY");
    			prepareTransactionalConnection(con, definition);
    			//激活事务状态
    			txObject.getConnectionHolder().setTransactionActive(true);
    
    			//设置超时
    			int timeout = determineTimeout(definition);
    			if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
    				txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
    			}
    
    			// Bind the connection holder to the thread.
    			//如果为新建ConnectionHolder,将数据源和ConnectionHolder绑定,并存放到ThreadLocal
    			if (txObject.isNewConnectionHolder()) {
    				TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
    			}
    		}
    
    		catch (Throwable ex) {
    			//上面执行异常,并且为新建的ConnectionHolder,归还连接并清空事务中的ConnectionHolder
    			if (txObject.isNewConnectionHolder()) {
    				DataSourceUtils.releaseConnection(con, obtainDataSource());
    				txObject.setConnectionHolder(null, false);
    			}
    			throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
    		}
    	}
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64

    prepareSynchronization根据需要初始化事务同步,其实就是在ThreadLocal中设置一些属性

    protected void prepareSynchronization(DefaultTransactionStatus status, TransactionDefinition definition) {
    		if (status.isNewSynchronization()) {
    			TransactionSynchronizationManager.setActualTransactionActive(status.hasTransaction());
    			TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(
    					definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT ?
    							definition.getIsolationLevel() : null);
    			TransactionSynchronizationManager.setCurrentTransactionReadOnly(definition.isReadOnly());
    			TransactionSynchronizationManager.setCurrentTransactionName(definition.getName());
    			TransactionSynchronizationManager.initSynchronization();
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3.5.2 第二种情况-事务一开始存在

    在UserService的test方法和b方法添加了@Transactional注解,并且在test方法还调用了b方法,那么事务是存在的

    @Component
    public class UserService {
    
    	@Autowired
    	private JdbcTemplate jdbcTemplate;
    
    	@Autowired
    	private UserService userService;
    
    	@Transactional
    	public void test(){
    		jdbcTemplate.execute("insert into student values(2,'1')");
    		userService.b();
    	}
    
    	@Transactional
    	public void b(){
    		jdbcTemplate.execute("insert into student values(1,'1')");
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    使用AnnotationConfigApplicationContext去获取Bean并调用test方法

    public class MainClass {
    
        public static void main(String[] args) {
            AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
    		UserService userService = (UserService) context.getBean("userService");
    		userService.test();
    
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    当在test方法里面调用b方法时,又会进入advice事务过滤逻辑,isExistingTransaction(transaction) 判断会通过
    handleExistingTransaction方法处理已存在事务的情况

    	private TransactionStatus handleExistingTransaction(
    			TransactionDefinition definition, Object transaction, boolean debugEnabled)
    			throws TransactionException {
    		//如果是PROPAGATION_NEVER传播机制,抛异常
    		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
    			throw new IllegalTransactionStateException(
    					"Existing transaction found for transaction marked with propagation 'never'");
    		}
    		//如果是PROPAGATION_NOT_SUPPORTED传播机制,不支持事务
    		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
    			if (debugEnabled) {
    				logger.debug("Suspending current transaction");
    			}
    			//挂起,得到挂起对象,也就是上一个完整的事务对象相关信息,用于之后的恢复
    			//1.清空ConnectionHolder
    			//2.解绑数据源和ConnectionHolder的关系,也就是从ThreadLocal中移除绑定关系
    			Object suspendedResources = suspend(transaction);
    			boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
    			//设置TransactionStatus的false代表为不是新开事务
    			//返回一个新的事务状态对象Status
    			return prepareTransactionStatus(
    					definition, null, false, newSynchronization, debugEnabled, suspendedResources);
    		}
    		//如果是PROPAGATION_REQUIRES_NEW传播机制,开启新的事务
    		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
    			if (debugEnabled) {
    				logger.debug("Suspending current transaction, creating new transaction with name [" +
    						definition.getName() + "]");
    			}
    			//挂起,得到挂起对象,也就是上一个完整的事务对象相关信息,用于之后的恢复
    			SuspendedResourcesHolder suspendedResources = suspend(transaction);
    			try {
    				//开启新的事务
    				return startTransaction(definition, transaction, debugEnabled, suspendedResources);
    			}
    			catch (RuntimeException | Error beginEx) {
    				//恢复给定的事务
    				resumeAfterBeginException(transaction, suspendedResources, beginEx);
    				throw beginEx;
    			}
    		}
    		//如果是PROPAGATION_NESTED传播机制,嵌套,创建savepoint
    		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
    			//是否允许嵌套事务
    			if (!isNestedTransactionAllowed()) {
    				throw new NestedTransactionNotSupportedException(
    						"Transaction manager does not allow nested transactions by default - " +
    						"specify 'nestedTransactionAllowed' property with value 'true'");
    			}
    			if (debugEnabled) {
    				logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
    			}
    			//是否为嵌套事务使用保存点
    			if (useSavepointForNestedTransaction()) {
    				// Create savepoint within existing Spring-managed transaction,
    				// through the SavepointManager API implemented by TransactionStatus.
    				// Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
    				//使用已存在的事务去创建savepoint
    				DefaultTransactionStatus status =
    						prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
    				status.createAndHoldSavepoint();
    				return status;
    			}
    			else {
    			     //JTA不是使用savepoint来实现嵌套事务
    				// Nested transaction through nested begin and commit/rollback calls.
    				// Usually only for JTA: Spring synchronization might get activated here
    				// in case of a pre-existing JTA transaction.
    				return startTransaction(definition, transaction, debugEnabled, null);
    			}
    		}
    
    		// Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
    		if (debugEnabled) {
    			logger.debug("Participating in existing transaction");
    		}
    		if (isValidateExistingTransaction()) {
    			if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
    				Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
    				if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
    					Constants isoConstants = DefaultTransactionDefinition.constants;
    					throw new IllegalTransactionStateException("Participating transaction with definition [" +
    							definition + "] specifies isolation level which is incompatible with existing transaction: " +
    							(currentIsolationLevel != null ?
    									isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) :
    									"(unknown)"));
    				}
    			}
    			if (!definition.isReadOnly()) {
    				if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
    					throw new IllegalTransactionStateException("Participating transaction with definition [" +
    							definition + "] is not marked as read-only but existing transaction is");
    				}
    			}
    		}
    		boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
    		return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
    	}
    
    • 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
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98

    3.6 事务挂起与恢复

    createTransactionIfNecessary方法会返回TransactionInfo对象,该对象存在一个指针指向了旧的TransactionInfo对象,即为链表结构,小编觉得有点像是用到了链表实现的栈结构

    protected static final class TransactionInfo {
    
    		@Nullable
    		private final PlatformTransactionManager transactionManager;
    
    		@Nullable
    		private final TransactionAttribute transactionAttribute;
    
    		private final String joinpointIdentification;
    
    		@Nullable
    		private TransactionStatus transactionStatus;
    
    		//旧的事务信息对象
    		@Nullable
    		private TransactionInfo oldTransactionInfo;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在createTransactionIfNecessary方法中最后返回prepareTransactionInfo方法执行的结果,该方法

    	protected TransactionInfo prepareTransactionInfo(@Nullable PlatformTransactionManager tm,
    			@Nullable TransactionAttribute txAttr, String joinpointIdentification,
    			@Nullable TransactionStatus status) {
    
    		TransactionInfo txInfo = new TransactionInfo(tm, txAttr, joinpointIdentification);
    		if (txAttr != null) {
    			// We need a transaction for this method...
    			if (logger.isTraceEnabled()) {
    				logger.trace("Getting transaction for [" + txInfo.getJoinpointIdentification() + "]");
    			}
    			// The transaction manager will flag an error if an incompatible tx already exists.
    			txInfo.newTransactionStatus(status);
    		}
    		else {
    			// The TransactionInfo.hasTransaction() method will return false. We created it only
    			// to preserve the integrity of the ThreadLocal stack maintained in this class.
    			if (logger.isTraceEnabled()) {
    				logger.trace("No need to create transaction for [" + joinpointIdentification +
    						"]: This method is not transactional.");
    			}
    		}
    
    		// We always bind the TransactionInfo to the thread, even if we didn't create
    		// a new transaction here. This guarantees that the TransactionInfo stack
    		// will be managed correctly even if no transaction was created by this aspect.
    		//此处为关键地方
    		txInfo.bindToThread();
    		return txInfo;
    	}
    
    • 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

    bindToThread将TransactionInfo和Thread绑定

    private void bindToThread() {
    			// Expose current TransactionStatus, preserving any existing TransactionStatus
    			// for restoration after this transaction is complete.
    			//当前txinfo指向ThreadLocal获取到的,类似栈结果,入栈操作
    			this.oldTransactionInfo = transactionInfoHolder.get();
    			//重新将当前放入ThreadLocal
    			transactionInfoHolder.set(this);
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    再回过头看一开始的代码

    //获取txinfo对象
    TransactionInfo txInfo = createTransactionIfNecessary(ptm, 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.
    				//执行被代理对象的方法
    				retVal = invocation.proceedWithInvocation();
    			}
    			catch (Throwable ex) {
    				// target invocation exception
    				completeTransactionAfterThrowing(txInfo, ex);
    				throw ex;
    			}
    			finally {
    				//此处是关键
    				cleanupTransactionInfo(txInfo);
    			}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    cleanupTransactionInfo方法,重置ThreadLocal中txinfo对象

    protected void cleanupTransactionInfo(@Nullable TransactionInfo txInfo) {
    		if (txInfo != null) {
    			txInfo.restoreThreadLocalStatus();
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5

    restoreThreadLocalStatus该方法有点出栈的意思

    private void restoreThreadLocalStatus() {
    			// Use stack to restore old transaction TransactionInfo.
    			// Will be null if none was set.
    			//当前txinfo出栈,this.oldTransactionInfo入栈
    			transactionInfoHolder.set(this.oldTransactionInfo);
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    四、事务的传播机制

    4.1 PROPAGATION_REQUIRED

    如果不存在事务,则创建一个新的,如果存在,就使用当前的事务;也就是说使用的是同一个事务

    4.2 PROPAGATION_SUPPORTS

    如果不存在事务,则以非事务方式执行,如果存在,就使用当前的事务

    4.3 PROPAGATION_MANDATORY

    如果当前不存在事务,则抛出异常,如果存在,就使用当前的事务

    4.4 PROPAGATION_REQUIRES_NEW

    创建一个新事务,如果存在则挂起当前事务,当前事务执行完之后重新恢复旧事务

    4.5 PROPAGATION_NOT_SUPPORTED

    不支持事务,始终以非事务方式执行

    4.6 PROPAGATION_NEVER

    不支持事务,如果当前事务存在,则抛出异常

    4.7 PROPAGATION_NESTED

    如果当前事务存在,则在嵌套事务中执行,JDBC采用创建SavePoint保存点实现嵌套


    总结

    以上就是今天要讲的内容,本文介绍了Spring事务的实现原理及其注解@Transactional底层和传播机制原理

  • 相关阅读:
    C++之左值、右值、std::forward、std::move总结(二百五十)
    koa实战 (三):JWT --Token 登录验证
    Prometheus-3:一文详解promQL
    在由buildroot制作出来的根文件系统中移植sudo命令
    【深度学习实战(25)】搭建训练框架之ModelEMA
    九章云极DataCanvas公司入选可信开源大模型产业推进方阵首批成员
    滚动条样式修改
    upload-labs/Pass-07 未知后缀名解析漏洞复现
    apktool反编译及后续打包
    文件操作之文件下载(32)
  • 原文地址:https://blog.csdn.net/IUNIQUE/article/details/126775930