Spring Framework版本:5.2.8.RELEASE。
在分析Spring的事务源码之前,首先需要了解IoC(《较真儿学源码系列-Spring IoC核心流程源码分析》)和AOP(《较真儿学源码系列-Spring AOP核心流程源码分析》)的实现。
1 简介
前面分析了Spring中IoC和AOP的实现。IoC是整个Spring中的核心,而AOP在IoC的几个扩展点中实现了自己的代理逻辑。本文将会继续分析Spring中事务的实现。实际上,Spring中事务是通过AOP来实现的,借用了AOP的实现流程。之前分析AOP的时候知道各个通知都会作为一个拦截器,通过责任链和递归的方式来实现调用逻辑。而这里事务将会单独作为一个内置的拦截器,以此来实现自己内部的逻辑。但是这并不意味着它的实现很简单,Spring中事务的实现完全有理由将它单独写一篇文章来进行分析。
1.1 事务四大特性
数据库事务transaction正确执行的四个基本要素:原子性(Atomicity)、一致性(Correspondence)、隔离性(Isolation)、持久性(Durability),简称ACID。
1.1.1 原子性
整个事务中的所有操作,要么全部完成,要么全部不完成,不可能停滞在中间某个环节。事务在执行过程中发生错误,会被回滚(Rollback)到事务开始前的状态,就像这个事务从来没有执行过一样。
1.1.2 一致性
一个查询的结果必须与数据库在查询开始的状态一致。指数据库事务不能破坏关系数据的完整性以及业务逻辑上的一致性。事务执行的前后都是合法的数据状态,不会违背任何的数据完整性。事务的执行使得数据库从一种正确状态转换成另一种正确状态。例如对银行转账事务,不管事务成功还是失败,应该保证事务结束后与转帐前的存款总额一致。
1.1.3 隔离性
隔离状态执行事务,使它们好像是系统在给定时间内执行的唯一操作。即使数据库中有多个事务并发地执行,各个事务之间也不会互相影响,并且在并发状态下执行的事务和串行执行的事务产生的结果完全相同。如果有两个事务,运行在相同的时间内,执行相同的功能,事务的隔离性将确保每一事务在系统中都认为只有该事务在使用系统。
1.1.4 持久性
指的是只要事务成功结束,它对数据库所做的更新就必须永久保存下来。即使发生系统崩溃,重启数据库后,数据库还能恢复到事务成功结束时的状态。
1.2 事务隔离级别
1.2.1 读取未提交(Read Uncommitted)
在该隔离级别,所有事务都可以看到其他未提交事务的执行结果。本隔离级别很少用于实际应用,因为它的性能也不比其他级别好多少。读取未提交的数据,也被称之为脏读(Dirty Read)。
1.2.2 读取已提交(Read Committed)
这是大多数数据库系统的默认隔离级别(但不是MySQL默认的)。它满足了隔离的简单定义:一个事务只能看见其他已经提交事务所做的改变。这种隔离级别也导致所谓的不可重复读(Nonrepeatable Read)的现象出现:因为同一事务的其他实例在该实例处理期间可能会有新的commit,所以同一select可能返回不同结果。
1.2.3 可重复读(Repeatable Read)
这是MySQL的默认事务隔离级别,它确保同一事务的多个实例在并发读取数据时,会看到同样的数据行。不过理论上,这会导致另一个棘手的问题:幻读(Phantom Read)。简单地说,幻读指当用户读取某一范围的数据行时,另一个事务又在该范围内插入了新行,当用户再读取该范围的数据行时,会发现有新的“幻影”行出现。
1.2.4 串行化(Serializable)
这是最高的隔离级别,它通过强制事务排序,使之不可能相互冲突,从而解决幻读问题。简而言之,它是在每个读的数据行上加上共享锁。在这个级别,可能会导致大量的超时现象和锁竞争发生。
1.3 事务传播行为
事务传播行为 | 如果当前没有事务 | 如果当前已经有事务了 |
---|---|---|
REQUIRED(默认) | 创建一个事务 | 融入到这个事务中来 |
SUPPORTS | 以非事务的方式来执行 | 融入到这个事务中来 |
MANDATORY | 抛出异常 | 融入到这个事务中来 |
REQUIRES_NEW | 创建一个事务 | 挂起这个事务,并创建一个新事务 |
NOT_SUPPORTED | 以非事务的方式来执行 | 挂起这个事务 |
NEVER | 以非事务的方式来执行 | 抛出异常 |
NESTED | 创建一个事务 | 在嵌套事务里执行 |
2 @EnableTransactionManagement注解
开启事务需要添加@EnableTransactionManagement注解。老规矩,首先就来看一下其实现:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
boolean proxyTargetClass() default false;
AdviceMode mode() default AdviceMode.PROXY;
int order() default Ordered.LOWEST_PRECEDENCE;
}
可以看到第4行代码处@Import了一个类:TransactionManagementConfigurationSelector。继续来看一下它的实现:
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
@Override
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
//这里默认会走JDK的代理,也就是本条件中
return new String[]{AutoProxyRegistrar.class.getName(),
ProxyTransactionManagementConfiguration.class.getName()};
case ASPECTJ:
return new String[]{determineTransactionAspectClass()};
default:
return null;
}
}
private String determineTransactionAspectClass() {
return (ClassUtils.isPresent("javax.transaction.Transactional", getClass().getClassLoader()) ?
TransactionManagementConfigUtils.JTA_TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME :
TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME);
}
}
不同于之前分析AOP时、AspectJAutoProxyRegistrar是通过registerBeanDefinitions的方式注册的bean定义,事务这里是通过selectImports方法来注册的bean定义。完整的调用链:<init>(AnnotationConfigApplicationContext)->refresh(AbstractApplicationContext)->invokeBeanFactoryPostProcessors(AbstractApplicationContext)->invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate)->invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate)->postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor)->processConfigBeanDefinitions(ConfigurationClassPostProcessor)->parse(ConfigurationClassParser)->parse(ConfigurationClassParser)->processConfigurationClass(ConfigurationClassParser)->doProcessConfigurationClass(ConfigurationClassParser)->processImports(ConfigurationClassParser)->selectImports(AdviceModeImportSelector)->selectImports(TransactionManagementConfigurationSelector)
一般情况下我们不会使用AspectJ来实现事务,所以这里会走PROXY分支。可以看到,是引入了两个类:AutoProxyRegistrar和ProxyTransactionManagementConfiguration。下面分别来进行说明。
2.1 AutoProxyRegistrar
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");
/*
如果有mode和proxyTargetClass属性,并且mode的类型是AdviceMode,
proxyTargetClass的类型是Boolean的话
*/
if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() &&
Boolean.class == proxyTargetClass.getClass()) {
//找到标志置为true
candidateFound = true;
//如果使用的是JDK的代理的话
if (mode == AdviceMode.PROXY) {
/*
这里和AOP的源码一样,也是注册了一个AutoProxyCreator,只不过
这里注册的是InfrastructureAdvisorAutoProxyCreator
*/
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
if ((Boolean) proxyTargetClass) {
/*
如果proxyTargetClass为true的话,就往InfrastructureAdvisorAutoProxyCreator中
添加proxyTargetClass属性为TRUE
*/
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
return;
}
}
}
}
//如果一个注解都没找到,就输出一下日志
if (!candidateFound && logger.isInfoEnabled()) {
String name = getClass().getSimpleName();
logger.info(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));
}
}
}
registerBeanDefinitions方法的调用链我在之前分析AOP的源码文章中已经说过了,这里就不再赘述了。需要留意的是,在第34行代码处可以看到,和AOP一样是注册了一个AutoProxyCreator,只不过这里注册的是InfrastructureAdvisorAutoProxyCreator。继续来查看该方法的实现:
/**
* AopConfigUtils:
*/
@Nullable
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
return registerAutoProxyCreatorIfNecessary(registry, null);
}
@Nullable
public static BeanDefinition registerAutoProxyCreatorIfNecessary(
BeanDefinitionRegistry registry, @Nullable Object source) {
//往容器中注册InfrastructureAdvisorAutoProxyCreator这个bean定义
return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
}
@Nullable
private static BeanDefinition registerOrEscalateApcAsRequired(
Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
/*
如果看过之前我对AOP源码进行分析的文章的话,就可以知道AOP也是调用的本方法来注册bean定义。但是那个时候
传入的是AnnotationAwareAspectJAutoProxyCreator类。而如果同时开启AOP和事务的话,这里就会有两个
AutoProxyCreator。先进来的事务的AutoProxyCreator会在下面的第54行代码处进行注册,而后进来的AOP的
AutoProxyCreator判断发现此时已经有了AUTO_PROXY_CREATOR_BEAN_NAME这个名字的bean定义了,于是
就会进入到下面的if条件中
*/
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
//获取先进来的事务的bean定义
BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
/*
如果两个class的名字不一样的话(一个是InfrastructureAdvisorAutoProxyCreator,一个是
AnnotationAwareAspectJAutoProxyCreator,当然不一样)
*/
if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
//获取事务bean定义的优先级
int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
//获取AOP bean定义的优先级
int requiredPriority = findPriorityForClass(cls);
//谁的优先级大,beanClass就设置为谁
if (currentPriority < requiredPriority) {
apcDefinition.setBeanClassName(cls.getName());
}
}
return null;
}
/*
如果此时没有AUTO_PROXY_CREATOR_BEAN_NAME这个bean定义,
就往容器中注册InfrastructureAdvisorAutoProxyCreator这个bean定义
*/
RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
return beanDefinition;
}
/**
* 第39行和第41行代码处:
* 从下面的APC_PRIORITY_LIST中可以看到其中含有三个元素,索引为0的是事务的AutoProxyCreator,
* 索引为2的是AOP的AutoProxyCreator。而从本方法的实现中可以看出,优先级就是它们在APC_PRIORITY_LIST
* 中的索引位而已。也就是说,AOP的优先级要高于事务。而这就意味着,如果同时开启AOP和事务,最终使用的beanClass
* 将会是AOP的。这会导致一些微妙的差异,后面会看到这点
*/
private static int findPriorityForClass(@Nullable String className) {
for (int i = 0; i < APC_PRIORITY_LIST.size(); i++) {
Class<?> clazz = APC_PRIORITY_LIST.get(i);
if (clazz.getName().equals(className)) {
return i;
}
}
throw new IllegalArgumentException(
"Class name [" + className + "] is not a known auto-proxy creator class");
}
private static final List<Class<?>> APC_PRIORITY_LIST = new ArrayList<>(3);
static {
APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);
APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);
APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);
}
2.2 ProxyTransactionManagementConfiguration
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
/**
* 注入一个内部的事务增强器
*/
@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(
TransactionAttributeSource transactionAttributeSource, TransactionInterceptor transactionInterceptor) {
BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
advisor.setTransactionAttributeSource(transactionAttributeSource);
advisor.setAdvice(transactionInterceptor);
if (this.enableTx != null) {
advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
}
return advisor;
}
/**
* 注入一个注解事务属性源
*/
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public TransactionAttributeSource transactionAttributeSource() {
return new AnnotationTransactionAttributeSource();
}
/**
* 注入一个事务拦截器
*/
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public TransactionInterceptor transactionInterceptor(TransactionAttributeSource transactionAttributeSource) {
TransactionInterceptor interceptor = new TransactionInterceptor();
interceptor.setTransactionAttributeSource(transactionAttributeSource);
if (this.txManager != null) {
interceptor.setTransactionManager(this.txManager);
}
return interceptor;
}
}
可以看到,ProxyTransactionManagementConfiguration内部注册了三个bean:BeanFactoryTransactionAttributeSourceAdvisor、AnnotationTransactionAttributeSource和TransactionInterceptor。后面会看到它们的使用。
3 InfrastructureAdvisorAutoProxyCreator继承图
在上面AutoProxyRegistrar类中的registerBeanDefinitions方法中,注册了AnnotationAwareAspectJAutoProxyCreator。下面来看一下其继承图:
由上可见,InfrastructureAdvisorAutoProxyCreator的继承图大体上是和AOP的AnnotationAwareAspectJAutoProxyCreator是类似的,后置处理器的扩展进入点也都是一样的。所以下面就只来分析一下其中的差异点。
4 findCandidateAdvisors方法
完整的调用链:<init>(AnnotationConfigApplicationContext)->refresh(AbstractApplicationContext)->finishBeanFactoryInitialization(AbstractApplicationContext)->preInstantiateSingletons(DefaultListableBeanFactory)->getBean(AbstractBeanFactory)->doGetBean(AbstractBeanFactory)->getSingleton(DefaultSingletonBeanRegistry)->getObject(AbstractBeanFactory)->createBean(AbstractAutowireCapableBeanFactory)->resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory)->applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory)->postProcessBeforeInstantiation(AbstractAutoProxyCreator)->shouldSkip(AspectJAwareAdvisorAutoProxyCreator)->findCandidateAdvisors(AnnotationAwareAspectJAutoProxyCreator)
/**
* AnnotationAwareAspectJAutoProxyCreator:
*/
@Override
protected List<Advisor> findCandidateAdvisors() {
//找到事务相关的Advisor(之前在分析AOP源码中,该处返回的是空集合。而现在因为加入了事务管理,所以再来看看该方法的实现)
List<Advisor> advisors = super.findCandidateAdvisors();
if (this.aspectJAdvisorsBuilder != null) {
//构建切面Advisor(在事务管理中,这里返回的是空的集合)
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
}
return advisors;
}
/**
* AbstractAdvisorAutoProxyCreator:
* 第8行代码处:
*/
protected List<Advisor> findCandidateAdvisors() {
Assert.state(this.advisorRetrievalHelper != null, "No BeanFactoryAdvisorRetrievalHelper available");
//advisorRetrievalHelper是在AbstractAdvisorAutoProxyCreator类中的initBeanFactory方法中进行初始化的
return this.advisorRetrievalHelper.findAdvisorBeans();
}
/**
* BeanFactoryAdvisorRetrievalHelper:
*/
public List<Advisor> findAdvisorBeans() {
//找到缓存的Advisor名称
String[] advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
/*
在容器中获取实现了Advisor接口的实现类(在事务管理中会找到BeanFactoryTransactionAttributeSourceAdvisor,
也就是在上面ProxyTransactionManagementConfiguration配置类中注入的第一个bean)
*/
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
//加入到缓存中
this.cachedAdvisorBeanNames = advisorNames;
}
//如果没有找到,就退出(之前在AOP源码中因为没有事务管理,所以就会在这里返回空集合)
if (advisorNames.length == 0) {
return new ArrayList<>();
}
List<Advisor> advisors = new ArrayList<>();
for (String name : advisorNames) {
//判断bean是否是合适的
if (isEligibleBean(name)) {
//判断是不是正在被创建中
if (this.beanFactory.isCurrentlyInCreation(name)) {
if (logger.isTraceEnabled()) {
logger.trace("Skipping currently created advisor '" + name + "'");
}
} else {
try {
/*
如果不是正在被创建中,就调用getBean方法来构建这个
BeanFactoryTransactionAttributeSourceAdvisor
*/
advisors.add(this.beanFactory.getBean(name, Advisor.class));
} catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && this.beanFactory.isCurrentlyInCreation(bceBeanName)) {
if (logger.isTraceEnabled()) {
logger.trace("Skipping advisor '" + name +
"' with dependency on currently created bean: " + ex.getMessage());
}
continue;
}
}
throw ex;
}
}
}
}
return advisors;
}
/**
* AbstractAdvisorAutoProxyCreator:
* 第50行代码处:
*/
@Override
protected boolean isEligibleBean(String beanName) {
//这里会调用到上面导入的InfrastructureAdvisorAutoProxyCreator组件中的方法
return AbstractAdvisorAutoProxyCreator.this.isEligibleAdvisorBean(beanName);
}
/**
* InfrastructureAdvisorAutoProxyCreator:
* 上面说过:如果同时开启AOP和事务的话,会使用到AOP的AutoProxyCreator。而对于事务的AutoProxyCreator
* 来说的话,只覆写了isEligibleAdvisorBean方法(实际上也覆写了initBeanFactory方法,但它并不会影响主流程)
* 也就是本方法的实现。如果bean定义是Spring内置的话(ROLE_INFRASTRUCTURE),就认为它是合适的;而AOP的
* AutoProxyCreator中的isEligibleAdvisorBean方法只是会返回true而已。所以可能会导致某些不是Spring内置的
* bean也会添加到advisors中。当然,如果只是开启事务的话,就不会有这个问题
*/
@Override
protected boolean isEligibleAdvisorBean(String beanName) {
//如果beanFactory不为空,并且容器中包含当前这个bean定义,并且bean定义的角色为ROLE_INFRASTRUCTURE
return (this.beanFactory != null && this.beanFactory.containsBeanDefinition(beanName) &&
this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE);
}
5 matches方法
完整的调用链:<init>(AnnotationConfigApplicationContext)->refresh(AbstractApplicationContext)->finishBeanFactoryInitialization(AbstractApplicationContext)->preInstantiateSingletons(DefaultListableBeanFactory)->getBean(AbstractBeanFactory)->doGetBean(AbstractBeanFactory)->getSingleton(DefaultSingletonBeanRegistry)->getObject(AbstractBeanFactory)->createBean(AbstractAutowireCapableBeanFactory)->doCreateBean(AbstractAutowireCapableBeanFactory)->initializeBean(AbstractAutowireCapableBeanFactory)->applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory)->postProcessAfterInitialization(AbstractAutoProxyCreator)->wrapIfNecessary(AbstractAutoProxyCreator)->getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator)->findEligibleAdvisors(AbstractAdvisorAutoProxyCreator)->findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator)->findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator)->canApply(AbstractAdvisorAutoProxyCreator)->canApply(AbstractAdvisorAutoProxyCreator)->canApply(AbstractAdvisorAutoProxyCreator)->matches(TransactionAttributeSourcePointcut)
/**
* TransactionAttributeSourcePointcut:
*/
@Override
public boolean matches(Method method, Class<?> targetClass) {
//获取在ProxyTransactionManagementConfiguration中注入的TransactionAttributeSource
TransactionAttributeSource tas = getTransactionAttributeSource();
return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
/**
* AbstractFallbackTransactionAttributeSource:
* 第8行代码处:
*/
@Override
@Nullable
public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
//如果是Object类中的方法,就直接返回null
if (method.getDeclaringClass() == Object.class) {
return null;
}
//构建缓存key
Object cacheKey = getCacheKey(method, targetClass);
//先去缓存中获取
TransactionAttribute cached = this.attributeCache.get(cacheKey);
if (cached != null) {
//空事务属性就返回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.isTraceEnabled()) {
logger.trace("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
}
//最后放入到缓存中
this.attributeCache.put(cacheKey, txAttr);
}
return txAttr;
}
}
/**
* 第37行代码处:
*/
@Nullable
protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
//如果事务方法不是public的,就返回null
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
//如果方法是接口上的方法,则获取实现类上的对应方法
Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
//第一步:从实现类的方法上面找事务属性
TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
if (txAttr != null) {
return txAttr;
}
//第二步:如果没找到,从实现类上面找事务属性
txAttr = findTransactionAttribute(specificMethod.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
if (specificMethod != method) {
//第三步:如果没找到,从接口的方法上面找事务属性
txAttr = findTransactionAttribute(method);
if (txAttr != null) {
return txAttr;
}
//第四步:如果没找到,从接口上面找事务属性
txAttr = findTransactionAttribute(method.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
}
return null;
}
/**
* AnnotationTransactionAttributeSource:
* 第72行和第85行代码处:
*/
@Override
@Nullable
protected TransactionAttribute findTransactionAttribute(Method method) {
return determineTransactionAttribute(method);
}
/**
* 第106行和第183行代码处:
*/
@Nullable
protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) {
for (TransactionAnnotationParser parser : this.annotationParsers) {
//解析事务注释
TransactionAttribute attr = parser.parseTransactionAnnotation(element);
if (attr != null) {
return attr;
}
}
return null;
}
/**
* SpringTransactionAnnotationParser:
* 第116行代码处:
*/
@Override
@Nullable
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
//获取@Transactional注解
AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
element, Transactional.class, false, false);
if (attributes != null) {
//解析事务注释
return parseTransactionAnnotation(attributes);
} else {
return null;
}
}
/**
* 第136行代码处:
* 将@Transactional注解上的属性设置进RuleBasedTransactionAttribute中
*/
protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
Propagation propagation = attributes.getEnum("propagation");
rbta.setPropagationBehavior(propagation.value());
Isolation isolation = attributes.getEnum("isolation");
rbta.setIsolationLevel(isolation.value());
rbta.setTimeout(attributes.getNumber("timeout").intValue());
rbta.setReadOnly(attributes.getBoolean("readOnly"));
rbta.setQualifier(attributes.getString("value"));
List<RollbackRuleAttribute> rollbackRules = new ArrayList<>();
for (Class<?> rbRule : attributes.getClassArray("rollbackFor")) {
rollbackRules.add(new RollbackRuleAttribute(rbRule));
}
for (String rbRule : attributes.getStringArray("rollbackForClassName")) {
rollbackRules.add(new RollbackRuleAttribute(rbRule));
}
for (Class<?> rbRule : attributes.getClassArray("noRollbackFor")) {
rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
}
for (String rbRule : attributes.getStringArray("noRollbackForClassName")) {
rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
}
rbta.setRollbackRules(rollbackRules);
return rbta;
}
/**
* AnnotationTransactionAttributeSource:
* 第78行和第90行代码处:
*/
@Override
@Nullable
protected TransactionAttribute findTransactionAttribute(Class<?> clazz) {
//同上面第113行代码处
return determineTransactionAttribute(clazz);
}
6 invoke方法
完整的调用链:invoke(JdkDynamicAopProxy)->proceed(ReflectiveMethodInvocation)->invoke(TransactionInterceptor)
之前在分析AOP源码时,已经知道了proceed方法会利用责任链模式和递归的方式来调用各个通知和目标方法。而事务管理也会走到proceed方法中,只不过这里的拦截器就变成了TransactionInterceptor。下面来看一下它的invoke方法的实现:
/**
* TransactionInterceptor:
*/
@Override
@Nullable
public Object invoke(MethodInvocation invocation) throws Throwable {
//获取目标类
Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed);
}
/**
* TransactionAspectSupport:
*/
@Nullable
protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
final InvocationCallback invocation) throws Throwable {
//获取在ProxyTransactionManagementConfiguration中注入的TransactionAttributeSource
TransactionAttributeSource tas = getTransactionAttributeSource();
//获取事务属性(之前已经解析过了,所以这次是从缓存中获取)
final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
//获取事务管理器(自己配置的),事务底层的处理实现都是由PlatformTransactionManager的实现类实现的
final TransactionManager tm = determineTransactionManager(txAttr);
if (this.reactiveAdapterRegistry != null && tm instanceof ReactiveTransactionManager) {
ReactiveTransactionSupport txSupport = this.transactionSupportCache.computeIfAbsent(method, key -> {
if (KotlinDetector.isKotlinType(method.getDeclaringClass()) && KotlinDelegate.isSuspend(method)) {
throw new TransactionUsageException(
"Unsupported annotated transaction on suspending function detected: " + method +
". Use TransactionalOperator.transactional extensions instead.");
}
ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(method.getReturnType());
if (adapter == null) {
throw new IllegalStateException("Cannot apply reactive transaction to non-reactive return type: " +
method.getReturnType());
}
return new ReactiveTransactionSupport(adapter);
});
return txSupport.invokeWithinTransaction(
method, targetClass, invocation, txAttr, (ReactiveTransactionManager) tm);
}
PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
//获取方法签名,即上面设置进去的descriptor字段:全限定接口/类名+“.”+方法名
final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
/*
声明式事务处理
创建事务(有必要的话)
*/
TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
Object retVal;
try {
//这里实际上又会调用到ReflectiveMethodInvocation.proceed方法中,一般会执行到目标方法
retVal = invocation.proceedWithInvocation();
} catch (Throwable ex) {
//回滚处理
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
} finally {
cleanupTransactionInfo(txInfo);
}
if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
TransactionStatus status = txInfo.getTransactionStatus();
if (status != null && txAttr != null) {
retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
}
}
//提交事务
commitTransactionAfterReturning(txInfo);
return retVal;
} else {
//编程式事务处理
Object result;
final ThrowableHolder throwableHolder = new ThrowableHolder();
try {
result = ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> {
TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status);
try {
Object retVal = invocation.proceedWithInvocation();
if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
}
return retVal;
} catch (Throwable ex) {
if (txAttr.rollbackOn(ex)) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new ThrowableHolderException(ex);
}
} else {
throwableHolder.throwable = ex;
return null;
}
} finally {
cleanupTransactionInfo(txInfo);
}
});
} 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;
}
if (throwableHolder.throwable != null) {
throw throwableHolder.throwable;
}
return result;
}
}
/**
* 第55行代码处:
*/
@SuppressWarnings("serial")
protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
@Nullable TransactionAttribute txAttr, final String joinpointIdentification) {
//如果没有指定名称,则将方法签名作为事务名称
if (txAttr != null && txAttr.getName() == null) {
txAttr = new DelegatingTransactionAttribute(txAttr) {
@Override
public String getName() {
return joinpointIdentification;
}
};
}
TransactionStatus status = null;
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);
}
/**
* AbstractPlatformTransactionManager:
* 第151行代码处:
*/
@Override
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
throws TransactionException {
//如果事务属性为null,就创建一个默认的StaticTransactionDefinition
TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());
//获取事务对象
Object transaction = doGetTransaction();
boolean debugEnabled = logger.isDebugEnabled();
//如果此时已经存在事务的话(嵌套事务)
if (isExistingTransaction(transaction)) {
//就处理存在的事务
return handleExistingTransaction(def, transaction, debugEnabled);
}
//如果事务已经超时了,就抛出异常
if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
}
if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
//如果事务的传播行为是PROPAGATION_MANDATORY,并且当前没有事务,就抛出异常
throw new IllegalTransactionStateException(
"No existing transaction found for transaction marked with propagation 'mandatory'");
} else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
/*
PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW和PROPAGATION_NESTED会走进本if子句中
这里虽然是调用了suspend方法,但是因为传入的是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 {
/*
PROPAGATION_SUPPORTS、PROPAGATION_NOT_SUPPORTED和PROPAGATION_NEVER会走到这里
创建一个空事务
*/
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);
//第三个参数是true,说明是一个新事务
return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
}
}
/**
* DataSourceTransactionManager:
* 第175行代码处:
*/
@Override
protected Object doGetTransaction() {
//创建一个新的DataSourceTransactionObject对象
DataSourceTransactionObject txObject = new DataSourceTransactionObject();
//如果是嵌套事务的话,设置savepoint
txObject.setSavepointAllowed(isNestedTransactionAllowed());
//通过数据源从缓存中查找连接(首次获取为空)
ConnectionHolder conHolder =
(ConnectionHolder) TransactionSynchronizationManager.getResource(obtainDataSource());
//将连接设置为旧连接
txObject.setConnectionHolder(conHolder, false);
return txObject;
}
/**
* 第179行代码处:
*/
@Override
protected boolean isExistingTransaction(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
/*
可以看到,判断当前是否已经存在事务与否是通过判断是否含有ConnectionHolder,
以及其中的transactionActive属性是否为true来判断的
*/
return (txObject.hasConnectionHolder() && txObject.getConnectionHolder().isTransactionActive());
}
/**
* AbstractPlatformTransactionManager:
* 第181行代码处:
*/
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");
}
//这里会挂起外部事务并返回外部事务资源
Object suspendedResources = suspend(transaction);
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
//第三个参数是false,说明不是一个新事务
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()) {
/*
第三个参数是false,说明不是一个新事务。也就说明NESTED不是通过
创建一个新的事务的方式来实现的,而只是原事务的子事务而已
*/
DefaultTransactionStatus status =
prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
//在存在外部事务的情况下会建立一个savepoint
status.createAndHoldSavepoint();
return status;
} else {
//JTA事务走这个分支,创建新事务
return startTransaction(definition, transaction, debugEnabled, null);
}
}
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");
}
}
}
//如果传播行为是PROPAGATION_SUPPORTS、ROPAGATION_REQUIRED或PROPAGATION_MANDATORY,就融入到外部事务中
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
//第三个参数是false,说明不是一个新事务
return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}
/**
* 第207行、第296行和第325行代码处:
*/
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);
//将当前的事务信息缓存到ThreadLocal中
prepareSynchronization(status, definition);
return status;
}
/**
* DataSourceTransactionManager:
* 第370行代码处:
*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
//强转成DataSourceTransactionObject类型
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
Connection con = null;
try {
//txObject没有设置过ConnectionHolder,又或者需要与事务同步的话
if (!txObject.hasConnectionHolder() ||
txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
//就通过数据源获取数据库连接
Connection newCon = obtainDataSource().getConnection();
if (logger.isDebugEnabled()) {
logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
}
//将数据库连接包装成一个ConnectionHolder,并设置到txObject中
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());
//切换成手动提交
if (con.getAutoCommit()) {
txObject.setMustRestoreAutoCommit(true);
if (logger.isDebugEnabled()) {
logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
}
//关闭自动提交,开启手动提交
con.setAutoCommit(false);
}
//如果事务是只读的,先执行一条设置只读的SQL语句:"SET TRANSACTION READ ONLY"
prepareTransactionalConnection(con, definition);
//设置事务激活(transactionActive属性置为true)
txObject.getConnectionHolder().setTransactionActive(true);
//设置事务超时时间
int timeout = determineTimeout(definition);
if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
}
//将数据源和数据库连接绑定到TransactionSynchronizationManager上,也就是放到了ThreadLocal缓存中
if (txObject.isNewConnectionHolder()) {
TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
}
} catch (Throwable ex) {
if (txObject.isNewConnectionHolder()) {
DataSourceUtils.releaseConnection(con, obtainDataSource());
txObject.setConnectionHolder(null, false);
}
throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
}
}
/**
* AbstractPlatformTransactionManager:
* 第201行、第279行和第293行代码处:
*/
@Nullable
protected final SuspendedResourcesHolder suspend(@Nullable Object transaction) throws TransactionException {
if (TransactionSynchronizationManager.isSynchronizationActive()) {
//如果需要和外部事务同步的话,就挂起并停用所有的事务同步机制
List<TransactionSynchronization> suspendedSynchronizations = doSuspendSynchronization();
try {
Object suspendedResources = null;
if (transaction != null) {
//这里会将connectionHolder置为null,同时将外部事务的资源放进suspendedResources中
suspendedResources = doSuspend(transaction);
}
//获取并清除外部事务的各个属性
String name = TransactionSynchronizationManager.getCurrentTransactionName();
TransactionSynchronizationManager.setCurrentTransactionName(null);
boolean readOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
TransactionSynchronizationManager.setCurrentTransactionReadOnly(false);
Integer isolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(null);
boolean wasActive = TransactionSynchronizationManager.isActualTransactionActive();
TransactionSynchronizationManager.setActualTransactionActive(false);
//把上面获取到的外部事务属性封装进SuspendedResourcesHolder中并返回
return new SuspendedResourcesHolder(
suspendedResources, suspendedSynchronizations, name, readOnly, isolationLevel, wasActive);
} catch (RuntimeException | Error ex) {
doResumeSynchronization(suspendedSynchronizations);
throw ex;
}
} else if (transaction != null) {
//如果不需要同步的话,就只是在做清空connectionHolder,并返回一个空属性的SuspendedResourcesHolder而已
Object suspendedResources = doSuspend(transaction);
return new SuspendedResourcesHolder(suspendedResources);
} else {
//否则就什么也不做
return null;
}
}
/**
* 第450行代码处:
*/
private List<TransactionSynchronization> doSuspendSynchronization() {
//获取当前线程中所有的事务同步
List<TransactionSynchronization> suspendedSynchronizations =
TransactionSynchronizationManager.getSynchronizations();
//遍历去逐个进行挂起
for (TransactionSynchronization synchronization : suspendedSynchronizations) {
synchronization.suspend();
}
//清理同步
TransactionSynchronizationManager.clearSynchronization();
return suspendedSynchronizations;
}
/**
* DataSourceTransactionManager:
* 第455行和第475行代码处:
*/
@Override
protected Object doSuspend(Object transaction) {
DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
//将外部事务的connectionHolder置为null
txObject.setConnectionHolder(null);
//同时从ThreadLocal缓存中解绑,并返回外部事务的资源
return TransactionSynchronizationManager.unbindResource(obtainDataSource());
}
/**
* TransactionAspectSupport:
* 第63行代码处:
*/
protected void completeTransactionAfterThrowing(@Nullable TransactionInfo txInfo, Throwable ex) {
if (txInfo != null && txInfo.getTransactionStatus() != null) {
if (logger.isTraceEnabled()) {
logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
"] after exception: " + ex);
}
if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
/*
默认情况下只有RuntimeException和Error及其子类才能回滚,
而如果配置了@Transactional注解中的rollbackFor属性的话会进行匹配
*/
try {
//通过事务管理器来进行回滚
txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
} catch (TransactionSystemException ex2) {
logger.error("Application exception overridden by rollback exception", ex);
ex2.initApplicationException(ex);
throw ex2;
} catch (RuntimeException | Error ex2) {
logger.error("Application exception overridden by rollback exception", ex);
throw ex2;
}
} else {
//不满足回滚条件的,会照样提交(如果rollbackOnly属性为true的话,还是会再次回滚的)
try {
txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
} catch (TransactionSystemException ex2) {
logger.error("Application exception overridden by commit exception", ex);
ex2.initApplicationException(ex);
throw ex2;
} catch (RuntimeException | Error ex2) {
logger.error("Application exception overridden by commit exception", ex);
throw ex2;
}
}
}
}
/**
* AbstractPlatformTransactionManager:
* 第529行代码处:
*/
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
processRollback(defStatus, false);
}
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
triggerBeforeCompletion(status);
if (status.hasSavepoint()) {
//如果有savepoint的话,说明是NESTED事务的子事务
if (status.isDebug()) {
logger.debug("Rolling back transaction to savepoint");
}
//就只回滚到savepoint
status.rollbackToHeldSavepoint();
} else if (status.isNewTransaction()) {
//如果是新事务(REQUIRES_NEW事务的子事务会进入到这里)
if (status.isDebug()) {
logger.debug("Initiating transaction rollback");
}
//就直接回滚
doRollback(status);
} else {
//否则就是在融入外部事务中时失败的
if (status.hasTransaction()) {
if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
if (status.isDebug()) {
logger.debug("Participating transaction failed - marking existing transaction as rollback-only");
}
//设置一下rollbackOnly属性为true,并不会立即回滚,而是在跳回到外部事务时回滚
doSetRollbackOnly(status);
} else {
if (status.isDebug()) {
logger.debug("Participating transaction failed - letting transaction originator decide on rollback");
}
}
} else {
logger.debug("Should roll back transaction but cannot - no transaction available");
}
if (!isFailEarlyOnGlobalRollbackOnly()) {
unexpectedRollback = false;
}
}
} catch (RuntimeException | Error ex) {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
throw ex;
}
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction rolled back because it has been marked as rollback-only");
}
} finally {
//清理工作,同时在该方法内部还会做一步工作:在子事务执行完毕后跳回到外部事务时,恢复外部事务的属性资源
cleanupAfterCompletion(status);
}
}
/**
* TransactionAspectSupport:
* 第77行代码处:
*/
protected void commitTransactionAfterReturning(@Nullable TransactionInfo txInfo) {
if (txInfo != null && txInfo.getTransactionStatus() != null) {
if (logger.isTraceEnabled()) {
logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "]");
}
//通过事务管理器来进行提交
txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
}
}
/**
* AbstractPlatformTransactionManager:
* 第541行和第638行代码处:
*/
@Override
public final void commit(TransactionStatus status) throws TransactionException {
//如果事务已经完成了,就抛出异常
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
"Transaction is already completed - do not call commit or rollback more than once per transaction");
}
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
/*
如果rollbackOnly属性为true的话,还是会再次回滚的(之前在上面第598行代码处,设置了rollbackOnly属性为true,
当时并不会立即回滚,而是延迟到了此时也就是外部事务提交的时候会回滚)
*/
if (defStatus.isLocalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Transactional code has requested rollback");
}
processRollback(defStatus, false);
return;
}
//全局事务标记为仅回滚,但在这里却请求提交。所以也进行回滚去吧
if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
if (defStatus.isDebug()) {
logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
}
processRollback(defStatus, true);
return;
}
//不属于上面的情况,就处理提交
processCommit(defStatus);
}
private void processCommit(DefaultTransactionStatus status) throws TransactionException {
try {
boolean beforeCompletionInvoked = false;
try {
boolean unexpectedRollback = false;
prepareForCommit(status);
triggerBeforeCommit(status);
triggerBeforeCompletion(status);
beforeCompletionInvoked = true;
if (status.hasSavepoint()) {
//如果有savepoint的话,说明是NESTED事务的子事务
if (status.isDebug()) {
logger.debug("Releasing transaction savepoint");
}
unexpectedRollback = status.isGlobalRollbackOnly();
/*
那么就仅仅是释放savepoint,而不做提交(NESTED事务只会在外部事务成功时才进行提交,
说明NESTED事务自始至终就只是一个事务而已,只不过是通过savepoint机制来进行分割的)
*/
status.releaseHeldSavepoint();
} else if (status.isNewTransaction()) {
//如果是新事务
if (status.isDebug()) {
logger.debug("Initiating transaction commit");
}
unexpectedRollback = status.isGlobalRollbackOnly();
//就直接提交
doCommit(status);
} else if (isFailEarlyOnGlobalRollbackOnly()) {
unexpectedRollback = status.isGlobalRollbackOnly();
}
/*
像PROPAGATION_REQUIRED、PROPAGATION_SUPPORTS或PROPAGATION_MANDATORY这几种传播行为下的子事务
是不会走入到上面的if分支中的。也就是提交的时候什么也不做,会在外部事务中一起做提交
*/
if (unexpectedRollback) {
throw new UnexpectedRollbackException(
"Transaction silently rolled back because it has been marked as rollback-only");
}
} catch (UnexpectedRollbackException ex) {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
throw ex;
} catch (TransactionException ex) {
if (isRollbackOnCommitFailure()) {
doRollbackOnCommitException(status, ex);
} else {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
}
throw ex;
} catch (RuntimeException | Error ex) {
if (!beforeCompletionInvoked) {
triggerBeforeCompletion(status);
}
doRollbackOnCommitException(status, ex);
throw ex;
}
try {
triggerAfterCommit(status);
} finally {
triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
}
} finally {
//清理工作,同时在该方法内部还会做一步工作:在子事务执行完毕后跳回到外部事务时,恢复外部事务的属性资源
cleanupAfterCompletion(status);
}
}
原创不易,未得准许,请勿转载,翻版必究