Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
S
Spring_resource_analysis
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
WeifengSun
Spring_resource_analysis
Commits
f1543be3
Commit
f1543be3
authored
Oct 03, 2022
by
SunWei峰
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
没有offer怎么办?焦虑啊,先继续学习Spring吧
parent
02d69ecd
Hide whitespace changes
Inline
Side-by-side
Showing
15 changed files
with
106 additions
and
7 deletions
+106
-7
spring-framework-main/spring-aop/src/main/java/org/springframework/aop/config/AopConfigUtils.java
+2
-0
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/AdviceModeImportSelector.java
+3
-1
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/AutoProxyRegistrar.java
+5
-0
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
+4
-0
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
+10
-2
spring-framework-main/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java
+4
-0
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSource.java
+3
-0
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.java
+3
-0
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/SpringTransactionAnnotationParser.java
+2
-0
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/TransactionManagementConfigurationSelector.java
+3
-0
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
+7
-0
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java
+29
-1
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAttributeSourcePointcut.java
+4
-0
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/support/AbstractPlatformTransactionManager.java
+26
-3
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/support/DefaultTransactionStatus.java
+1
-0
No files found.
spring-framework-main/spring-aop/src/main/java/org/springframework/aop/config/AopConfigUtils.java
View file @
f1543be3
...
...
@@ -59,8 +59,10 @@ public abstract class AopConfigUtils {
static
{
// Set up the escalation list...
// 下表越大,优先级越高
// 事务使用
APC_PRIORITY_LIST
.
add
(
InfrastructureAdvisorAutoProxyCreator
.
class
);
APC_PRIORITY_LIST
.
add
(
AspectJAwareAdvisorAutoProxyCreator
.
class
);
// Spring aop 使用
APC_PRIORITY_LIST
.
add
(
AnnotationAwareAspectJAutoProxyCreator
.
class
);
}
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/AdviceModeImportSelector.java
View file @
f1543be3
...
...
@@ -64,16 +64,18 @@ public abstract class AdviceModeImportSelector<A extends Annotation> implements
*/
@Override
public
final
String
[]
selectImports
(
AnnotationMetadata
importingClassMetadata
)
{
// 获取注解类型,这里是 EnableTransactionManagement
Class
<?>
annType
=
GenericTypeResolver
.
resolveTypeArgument
(
getClass
(),
AdviceModeImportSelector
.
class
);
Assert
.
state
(
annType
!=
null
,
"Unresolvable type argument for AdviceModeImportSelector"
);
// 解析出 @EnableTransactionManagement 注解的参数
AnnotationAttributes
attributes
=
AnnotationConfigUtils
.
attributesFor
(
importingClassMetadata
,
annType
);
if
(
attributes
==
null
)
{
throw
new
IllegalArgumentException
(
String
.
format
(
"@%s is not present on importing class '%s' as expected"
,
annType
.
getSimpleName
(),
importingClassMetadata
.
getClassName
()));
}
// 获取 mode 属性。EnableTransactionManagement 默认 mode = AdviceMode.PROXY
AdviceMode
adviceMode
=
attributes
.
getEnum
(
getAdviceModeAttributeName
());
String
[]
imports
=
selectImports
(
adviceMode
);
if
(
imports
==
null
)
{
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/AutoProxyRegistrar.java
View file @
f1543be3
...
...
@@ -58,19 +58,24 @@ public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
@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、proxyTargetClass 属性
Object
mode
=
candidate
.
get
(
"mode"
);
Object
proxyTargetClass
=
candidate
.
get
(
"proxyTargetClass"
);
if
(
mode
!=
null
&&
proxyTargetClass
!=
null
&&
AdviceMode
.
class
==
mode
.
getClass
()
&&
Boolean
.
class
==
proxyTargetClass
.
getClass
())
{
candidateFound
=
true
;
// 判断如果是 Proxy 模式,也就是默认模式,注册自动代理创建器
if
(
mode
==
AdviceMode
.
PROXY
)
{
AopConfigUtils
.
registerAutoProxyCreatorIfNecessary
(
registry
);
// 如果需要代理目标列,则强制自动代理创建者使用类代理
if
((
Boolean
)
proxyTargetClass
)
{
AopConfigUtils
.
forceAutoProxyCreatorToUseClassProxying
(
registry
);
return
;
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
View file @
f1543be3
...
...
@@ -145,14 +145,18 @@ class ConfigurationClassBeanDefinitionReader {
return
;
}
// 1. 如果配置是被引入的(被 @Import 或者其他配置类内部引入)
if
(
configClass
.
isImported
())
{
registerBeanDefinitionForImportedConfigurationClass
(
configClass
);
}
// 2. 遍历配置类中的所有 BeanMethod方法
for
(
BeanMethod
beanMethod
:
configClass
.
getBeanMethods
())
{
loadBeanDefinitionsForBeanMethod
(
beanMethod
);
}
// 3. 加载 通过 @ImportResource 的 获取的bean
loadBeanDefinitionsFromImportedResources
(
configClass
.
getImportedResources
());
// 4. 加载 通过 @Import 的 获取的bean
// AOP 自动代理创建器的注册就在这一步
loadBeanDefinitionsFromRegistrars
(
configClass
.
getImportBeanDefinitionRegistrars
());
}
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
View file @
f1543be3
...
...
@@ -324,7 +324,7 @@ class ConfigurationClassParser {
}
// Process any @Import annotations
// @Import、
@ImportSelector、@ImportBeanDefinitionRegistrar
都在这儿
// @Import、
ImportSelector、ImportBeanDefinitionRegistrar 注解和接口
都在这儿
processImports
(
configClass
,
sourceClass
,
getImports
(
sourceClass
),
filter
,
true
);
// Process any @ImportResource annotations
...
...
@@ -580,6 +580,10 @@ class ConfigurationClassParser {
private
void
processImports
(
ConfigurationClass
configClass
,
SourceClass
currentSourceClass
,
Collection
<
SourceClass
>
importCandidates
,
Predicate
<
String
>
exclusionFilter
,
boolean
checkForCircularImports
)
{
// @Import : 可以通过 @Import(XXX.class) 的方式,将指定的类注册到容器中,并且会执行下面两个解析
// ImportSelector : Spring 会将 ImportSelector#selectImports 方法返回的内容通过反射加载到容器中
// ImportBeanDefinitionRegistrar : 可以通过 registerBeanDefinitions 方法声明BeanDefinition 并自己注册到Spring容器中
// 比如:MyBatis 中的 AutoConfiguredMapperScannerRegistrar 对 @Mapper 修饰类的注册过程
if
(
importCandidates
.
isEmpty
())
{
return
;
...
...
@@ -595,7 +599,7 @@ class ConfigurationClassParser {
for
(
SourceClass
candidate
:
importCandidates
)
{
if
(
candidate
.
isAssignable
(
ImportSelector
.
class
))
{
// Candidate class is an ImportSelector -> delegate to it to determine imports
// 判断是否是
ImportSelector类型。ImportSelector 则需要调用
selectImports 方法来获取需要注入的类。
// 判断是否是
ImportSelector 类型。ImportSelector 则需要调用
selectImports 方法来获取需要注入的类。
Class
<?>
candidateClass
=
candidate
.
loadClass
();
ImportSelector
selector
=
ParserStrategyUtils
.
instantiateClass
(
candidateClass
,
ImportSelector
.
class
,
this
.
environment
,
this
.
resourceLoader
,
this
.
registry
);
...
...
@@ -607,6 +611,8 @@ class ConfigurationClassParser {
this
.
deferredImportSelectorHandler
.
handle
(
configClass
,
(
DeferredImportSelector
)
selector
);
}
else
{
// 调用 Springboot 的自动配置,调用 AutoConfigurationImportSelector # selectImports()
// 各个 selectImports() 都是在这儿调用,包括事务等
String
[]
importClassNames
=
selector
.
selectImports
(
currentSourceClass
.
getMetadata
());
Collection
<
SourceClass
>
importSourceClasses
=
asSourceClasses
(
importClassNames
,
exclusionFilter
);
// 调用 selectImports 方法获取需要引入的类,并递归再次处理。
...
...
@@ -908,6 +914,7 @@ class ConfigurationClassParser {
*/
public
Iterable
<
Group
.
Entry
>
getImports
()
{
for
(
DeferredImportSelectorHolder
deferredImport
:
this
.
deferredImports
)
{
// 调用 SpringBoot 的 selectImports()
this
.
group
.
process
(
deferredImport
.
getConfigurationClass
().
getMetadata
(),
deferredImport
.
getImportSelector
());
}
...
...
@@ -933,6 +940,7 @@ class ConfigurationClassParser {
@Override
public
void
process
(
AnnotationMetadata
metadata
,
DeferredImportSelector
selector
)
{
// 这里调用 SpringBoot 的 selectImports()
for
(
String
importClassName
:
selector
.
selectImports
(
metadata
))
{
this
.
imports
.
add
(
new
Entry
(
metadata
,
importClassName
));
}
...
...
spring-framework-main/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java
View file @
f1543be3
...
...
@@ -241,9 +241,12 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
@Override
protected
Object
doGetTransaction
()
{
DataSourceTransactionObject
txObject
=
new
DataSourceTransactionObject
();
// 是否允许设置保存点:决定是否允许嵌套事务的存在
txObject
.
setSavepointAllowed
(
isNestedTransactionAllowed
());
// 如果当前线程已经记录了数据库连接则使用原有连接
ConnectionHolder
conHolder
=
(
ConnectionHolder
)
TransactionSynchronizationManager
.
getResource
(
obtainDataSource
());
// false 代表非新创建连接
txObject
.
setConnectionHolder
(
conHolder
,
false
);
return
txObject
;
}
...
...
@@ -251,6 +254,7 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan
@Override
protected
boolean
isExistingTransaction
(
Object
transaction
)
{
DataSourceTransactionObject
txObject
=
(
DataSourceTransactionObject
)
transaction
;
// 存在连接,且其 transactionActive 属性不为空,isTransactionActive() 中的返回是 transactionActive = true
return
(
txObject
.
hasConnectionHolder
()
&&
txObject
.
getConnectionHolder
().
isTransactionActive
());
}
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSource.java
View file @
f1543be3
...
...
@@ -91,6 +91,7 @@ public class AnnotationTransactionAttributeSource extends AbstractFallbackTransa
*/
public
AnnotationTransactionAttributeSource
(
boolean
publicMethodsOnly
)
{
this
.
publicMethodsOnly
=
publicMethodsOnly
;
// 可以看到,无论什么场景 SpringTransactionAnnotationParser 都是必定存在的解析器
if
(
jta12Present
||
ejb3Present
)
{
this
.
annotationParsers
=
new
LinkedHashSet
<>(
4
);
this
.
annotationParsers
.
add
(
new
SpringTransactionAnnotationParser
());
...
...
@@ -140,6 +141,8 @@ public class AnnotationTransactionAttributeSource extends AbstractFallbackTransa
@Override
public
boolean
isCandidateClass
(
Class
<?>
targetClass
)
{
for
(
TransactionAnnotationParser
parser
:
this
.
annotationParsers
)
{
// 这里是 SpringTransactionAnnotationParser 类型,SpringTransactionAnnotationParser#isCandidateClass
// 中判断了目标类是否存在 org.springframework.transaction.annotation.Transactional 注解
if
(
parser
.
isCandidateClass
(
targetClass
))
{
return
true
;
}
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/ProxyTransactionManagementConfiguration.java
View file @
f1543be3
...
...
@@ -39,6 +39,7 @@ import org.springframework.transaction.interceptor.TransactionInterceptor;
@Role
(
BeanDefinition
.
ROLE_INFRASTRUCTURE
)
public
class
ProxyTransactionManagementConfiguration
extends
AbstractTransactionManagementConfiguration
{
// 事务的增强器,该方法是否开始事务,是否需要代理该类都在该类中判断
@Bean
(
name
=
TransactionManagementConfigUtils
.
TRANSACTION_ADVISOR_BEAN_NAME
)
@Role
(
BeanDefinition
.
ROLE_INFRASTRUCTURE
)
public
BeanFactoryTransactionAttributeSourceAdvisor
transactionAdvisor
(
...
...
@@ -53,6 +54,7 @@ public class ProxyTransactionManagementConfiguration extends AbstractTransaction
return
advisor
;
}
// 保存了事务相关的一些信息资源。
@Bean
@Role
(
BeanDefinition
.
ROLE_INFRASTRUCTURE
)
public
TransactionAttributeSource
transactionAttributeSource
()
{
...
...
@@ -60,6 +62,7 @@ public class ProxyTransactionManagementConfiguration extends AbstractTransaction
return
new
AnnotationTransactionAttributeSource
(
false
);
}
// 事务拦截器,事务生成代理类时使用的代理拦截器,编写了事务的规则
@Bean
@Role
(
BeanDefinition
.
ROLE_INFRASTRUCTURE
)
public
TransactionInterceptor
transactionInterceptor
(
TransactionAttributeSource
transactionAttributeSource
)
{
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/SpringTransactionAnnotationParser.java
View file @
f1543be3
...
...
@@ -51,6 +51,7 @@ public class SpringTransactionAnnotationParser implements TransactionAnnotationP
@Override
@Nullable
public
TransactionAttribute
parseTransactionAnnotation
(
AnnotatedElement
element
)
{
// 获取事务注解的属性信息
AnnotationAttributes
attributes
=
AnnotatedElementUtils
.
findMergedAnnotationAttributes
(
element
,
Transactional
.
class
,
false
,
false
);
if
(
attributes
!=
null
)
{
...
...
@@ -66,6 +67,7 @@ public class SpringTransactionAnnotationParser implements TransactionAnnotationP
}
protected
TransactionAttribute
parseTransactionAnnotation
(
AnnotationAttributes
attributes
)
{
// 解析各种属性信息
RuleBasedTransactionAttribute
rbta
=
new
RuleBasedTransactionAttribute
();
Propagation
propagation
=
attributes
.
getEnum
(
"propagation"
);
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/annotation/TransactionManagementConfigurationSelector.java
View file @
f1543be3
...
...
@@ -47,7 +47,10 @@ public class TransactionManagementConfigurationSelector extends AdviceModeImport
protected
String
[]
selectImports
(
AdviceMode
adviceMode
)
{
switch
(
adviceMode
)
{
case
PROXY:
// 注册了 InfrastructureAdvisorAutoProxyCreator 自动代理创建器
return
new
String
[]
{
AutoProxyRegistrar
.
class
.
getName
(),
// 注册了事务实现的核心 Bean,包括 BeanFactoryTransactionAttributeSourceAdvisor、
// TransactionAttributeSource、TransactionInterceptor 等
ProxyTransactionManagementConfiguration
.
class
.
getName
()};
case
ASPECTJ:
return
new
String
[]
{
determineTransactionAspectClass
()};
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/interceptor/AbstractFallbackTransactionAttributeSource.java
View file @
f1543be3
...
...
@@ -102,11 +102,13 @@ public abstract class AbstractFallbackTransactionAttributeSource
@Override
@Nullable
public
TransactionAttribute
getTransactionAttribute
(
Method
method
,
@Nullable
Class
<?>
targetClass
)
{
// 判断声明类是否是 Object
if
(
method
.
getDeclaringClass
()
==
Object
.
class
)
{
return
null
;
}
// First, see if we have a cached value.
// 尝试从缓冲中获取
Object
cacheKey
=
getCacheKey
(
method
,
targetClass
);
TransactionAttribute
cached
=
this
.
attributeCache
.
get
(
cacheKey
);
if
(
cached
!=
null
)
{
...
...
@@ -163,26 +165,31 @@ public abstract class AbstractFallbackTransactionAttributeSource
@Nullable
protected
TransactionAttribute
computeTransactionAttribute
(
Method
method
,
@Nullable
Class
<?>
targetClass
)
{
// Don't allow non-public methods, as configured.
// 按照配置,不允许使用非 public 方法
if
(
allowPublicMethodsOnly
()
&&
!
Modifier
.
isPublic
(
method
.
getModifiers
()))
{
return
null
;
}
// The method may be on an interface, but we need attributes from the target class.
// If the target class is null, the method will be unchanged.
// 找到真实对象上的方法
Method
specificMethod
=
AopUtils
.
getMostSpecificMethod
(
method
,
targetClass
);
// First try is the method in the target class.
// 寻找实现类方法的事务属性,即类方法判断是否有声明事务属性并解析注解
TransactionAttribute
txAttr
=
findTransactionAttribute
(
specificMethod
);
if
(
txAttr
!=
null
)
{
return
txAttr
;
}
// Second try is the transaction attribute on the target class.
// 在类上判断并解析事务注解
txAttr
=
findTransactionAttribute
(
specificMethod
.
getDeclaringClass
());
if
(
txAttr
!=
null
&&
ClassUtils
.
isUserLevelMethod
(
method
))
{
return
txAttr
;
}
// 如果存在接口方法,则从接口方法中尝试去获取事务属性
if
(
specificMethod
!=
method
)
{
// Fallback is to look at the original method.
txAttr
=
findTransactionAttribute
(
method
);
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java
View file @
f1543be3
...
...
@@ -337,10 +337,19 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
final
InvocationCallback
invocation
)
throws
Throwable
{
// If the transaction attribute is null, the method is non-transactional.
// 获取事务数据源,这里获取的数据源就是在 TransactionInterceptor 注入的时候的设置的属性
// transactionAttributeSource = AnnotationTransactionAttributeSource。
// 在 ProxyTransactionManagementConfiguration 中完成
TransactionAttributeSource
tas
=
getTransactionAttributeSource
();
// 1. 解析并获取对应的事务属性
final
TransactionAttribute
txAttr
=
(
tas
!=
null
?
tas
.
getTransactionAttribute
(
method
,
targetClass
)
:
null
);
// 2. 获取一个合适的 TransactionManager
// JPA还是JDBC等都实现自接口 PlatformTransactionManager
final
TransactionManager
tm
=
determineTransactionManager
(
txAttr
);
// 3. 对于反应式事务的处理
// 从 Spring Framework 5.2 M2开始,Spring 通过 ReactiveTransactionManagerSPI 支持响应式/反应式事务管理
if
(
this
.
reactiveAdapterRegistry
!=
null
&&
tm
instanceof
ReactiveTransactionManager
)
{
boolean
isSuspendingFunction
=
KotlinDetector
.
isSuspendingFunction
(
method
);
boolean
hasSuspendingFlowReturnType
=
isSuspendingFunction
&&
...
...
@@ -374,25 +383,35 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
return
result
;
}
// 判断 tm 是否是 PlatformTransactionManager 类型,是则强转,不是则抛出异常
PlatformTransactionManager
ptm
=
asPlatformTransactionManager
(
tm
);
// 构造方法的唯一标识(全路径了类名.方法)
final
String
joinpointIdentification
=
methodIdentification
(
method
,
targetClass
,
txAttr
);
// 4. 对不同事务情景的处理
// 声明式事务的处理
// 如果 txAttr 为空或者 tm 属于非 CallbackPreferringPlatformTransactionManager,执行目标增强
// 在 TransactionManager 上,CallbackPreferringPlatformTransactionManager
// 实现PlatformTransactionManager接口,暴露出一个方法用于执行事务处理中的回调
if
(
txAttr
==
null
||
!(
ptm
instanceof
CallbackPreferringPlatformTransactionManager
))
{
// Standard transaction demarcation with getTransaction and commit/rollback calls.
// 5.如果有必要,创建事务信息。主要由于事务的传播属性,所以这里并不一定会创建事务
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.
// 6. 执行被增强的方法
retVal
=
invocation
.
proceedWithInvocation
();
}
catch
(
Throwable
ex
)
{
// target invocation exception
// 7. 异常回滚
completeTransactionAfterThrowing
(
txInfo
,
ex
);
throw
ex
;
}
finally
{
// 8. 提交之前清除事务信息
cleanupTransactionInfo
(
txInfo
);
}
...
...
@@ -404,19 +423,24 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
}
}
// 9.提交事务
commitTransactionAfterReturning
(
txInfo
);
return
retVal
;
}
// 编程式事务(CallbackPreferringPlatformTransactionManager)的处理。这里的逻辑基本都被封装了
else
{
Object
result
;
final
ThrowableHolder
throwableHolder
=
new
ThrowableHolder
();
// It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
try
{
// 直接调用execute 方法。由于事务的提交回滚等操作都已经封装好了,所以这里并没有对事务进行详细的操作。
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
))
{
// Set rollback-only in case of Vavr failure matching our rollback rules...
...
...
@@ -441,6 +465,7 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
}
}
finally
{
// 清除事务信息
cleanupTransactionInfo
(
txInfo
);
}
});
...
...
@@ -580,6 +605,7 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
@Nullable
TransactionAttribute
txAttr
,
final
String
joinpointIdentification
)
{
// If no name specified, apply method identification as transaction name.
// 如果没有名称指定则使用方法唯一标识(外面之前封装的),并使用 DelegatingTransactionAttribute 封装 txAttr
if
(
txAttr
!=
null
&&
txAttr
.
getName
()
==
null
)
{
txAttr
=
new
DelegatingTransactionAttribute
(
txAttr
)
{
@Override
...
...
@@ -592,6 +618,7 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
TransactionStatus
status
=
null
;
if
(
txAttr
!=
null
)
{
if
(
tm
!=
null
)
{
// 获取事务的 TransactionStatus
status
=
tm
.
getTransaction
(
txAttr
);
}
else
{
...
...
@@ -601,6 +628,7 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init
}
}
}
// 构建 TransactionInfo(TransactionStatus、TransactionAttribute、TransactionManager 等属性更进一步封装)
return
prepareTransactionInfo
(
tm
,
txAttr
,
joinpointIdentification
,
status
);
}
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAttributeSourcePointcut.java
View file @
f1543be3
...
...
@@ -43,6 +43,7 @@ abstract class TransactionAttributeSourcePointcut extends StaticMethodMatcherPoi
@Override
public
boolean
matches
(
Method
method
,
Class
<?>
targetClass
)
{
// 调用 TransactionAttributeSource.getTransactionAttribute方法来匹配
TransactionAttributeSource
tas
=
getTransactionAttributeSource
();
return
(
tas
==
null
||
tas
.
getTransactionAttribute
(
method
,
targetClass
)
!=
null
);
}
...
...
@@ -85,12 +86,15 @@ abstract class TransactionAttributeSourcePointcut extends StaticMethodMatcherPoi
@Override
public
boolean
matches
(
Class
<?>
clazz
)
{
// 如果是一些基础类,则返回false
if
(
TransactionalProxy
.
class
.
isAssignableFrom
(
clazz
)
||
TransactionManager
.
class
.
isAssignableFrom
(
clazz
)
||
PersistenceExceptionTranslator
.
class
.
isAssignableFrom
(
clazz
))
{
return
false
;
}
// 调用 TransactionAttributeSource.isCandidateClass 方法来匹配
TransactionAttributeSource
tas
=
getTransactionAttributeSource
();
// 主要判断是否是候选类,即当前的的注解解析器 annotationParsers 是否可以解析当前类。
return
(
tas
==
null
||
tas
.
isCandidateClass
(
clazz
));
}
}
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/support/AbstractPlatformTransactionManager.java
View file @
f1543be3
...
...
@@ -344,32 +344,43 @@ public abstract class AbstractPlatformTransactionManager implements PlatformTran
// Use defaults if no transaction definition given.
TransactionDefinition
def
=
(
definition
!=
null
?
definition
:
TransactionDefinition
.
withDefaults
());
// 1. 获取事务
Object
transaction
=
doGetTransaction
();
boolean
debugEnabled
=
logger
.
isDebugEnabled
();
// 2. 判断当前线程是否存在事务,判断依据是当前线程记录的数据库连接不为空,且连接(connectionHolder)中的 transactionActive 属性 为true;
// 这个方法的实现在 DataSourceTransactionManager # isExistingTransaction。
if
(
isExistingTransaction
(
transaction
))
{
// Existing transaction found -> check propagation behavior to find out how to behave.
// 3.当前线程已经存在事务,则按照嵌套事务的逻辑处理
return
handleExistingTransaction
(
def
,
transaction
,
debugEnabled
);
}
// 到这里就表明当前线程没有事务存在了,即不会出现嵌套事务的情况了
// Check definition settings for new transaction.
// 事务超时验证
if
(
def
.
getTimeout
()
<
TransactionDefinition
.
TIMEOUT_DEFAULT
)
{
throw
new
InvalidTimeoutException
(
"Invalid transaction timeout"
,
def
.
getTimeout
());
}
// No existing transaction found -> check propagation behavior to find out how to proceed.
// 下面是针对事务传播属性进行处理了
// 4. 如果传播属性是 PROPAGATION_MANDATORY(mandatory)。但是当前线程又不存在事务,则抛出异常
if
(
def
.
getPropagationBehavior
()
==
TransactionDefinition
.
PROPAGATION_MANDATORY
)
{
throw
new
IllegalTransactionStateException
(
"No existing transaction found for transaction marked with propagation 'mandatory'"
);
}
// 5. 如果传播属性是PROPAGATION_REQUIRED 、PROPAGATION_REQUIRES_NEW 、PROPAGATION_NESTED(nested) 都需要新建事务
else
if
(
def
.
getPropagationBehavior
()
==
TransactionDefinition
.
PROPAGATION_REQUIRED
||
def
.
getPropagationBehavior
()
==
TransactionDefinition
.
PROPAGATION_REQUIRES_NEW
||
def
.
getPropagationBehavior
()
==
TransactionDefinition
.
PROPAGATION_NESTED
)
{
// 5.1. 进行空挂起。为了记录原有事务的状态,便于后续操作对事务的恢复。因为这里原先并不存在事务,所以进行空挂起
SuspendedResourcesHolder
suspendedResources
=
suspend
(
null
);
if
(
debugEnabled
)
{
logger
.
debug
(
"Creating new transaction with name ["
+
def
.
getName
()
+
"]: "
+
def
);
}
try
{
// 5.2.开启事务,并返回了事务状态
return
startTransaction
(
def
,
transaction
,
debugEnabled
,
suspendedResources
);
}
catch
(
RuntimeException
|
Error
ex
)
{
...
...
@@ -378,12 +389,14 @@ public abstract class AbstractPlatformTransactionManager implements PlatformTran
}
}
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
);
// 6. 构建事务信息
return
prepareTransactionStatus
(
def
,
null
,
true
,
newSynchronization
,
debugEnabled
,
null
);
}
}
...
...
@@ -409,28 +422,33 @@ public abstract class AbstractPlatformTransactionManager implements PlatformTran
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
);
// 准备事务信息
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
)
{
...
...
@@ -438,7 +456,7 @@ public abstract class AbstractPlatformTransactionManager implements PlatformTran
throw
beginEx
;
}
}
// 如果传播属性是 PROPAGATION_NESTED,则如果当前存在事务,则在嵌套事务内执行。否则自己创建事务
if
(
definition
.
getPropagationBehavior
()
==
TransactionDefinition
.
PROPAGATION_NESTED
)
{
if
(!
isNestedTransactionAllowed
())
{
throw
new
NestedTransactionNotSupportedException
(
...
...
@@ -448,12 +466,15 @@ public abstract class AbstractPlatformTransactionManager implements PlatformTran
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.
// 嵌入式事务的建立时便建立保存点
DefaultTransactionStatus
status
=
prepareTransactionStatus
(
definition
,
transaction
,
false
,
false
,
debugEnabled
,
null
);
// 创建设置保存点
status
.
createAndHoldSavepoint
();
return
status
;
}
...
...
@@ -461,6 +482,7 @@ public abstract class AbstractPlatformTransactionManager implements PlatformTran
// 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.
// 有些情况下是不能使用保存点操作,如 JTA,这时候就需要新建事务
return
startTransaction
(
definition
,
transaction
,
debugEnabled
,
null
);
}
}
...
...
@@ -469,6 +491,7 @@ public abstract class AbstractPlatformTransactionManager implements PlatformTran
if
(
debugEnabled
)
{
logger
.
debug
(
"Participating in existing transaction"
);
}
// 进行事务的合法性校验
if
(
isValidateExistingTransaction
())
{
if
(
definition
.
getIsolationLevel
()
!=
TransactionDefinition
.
ISOLATION_DEFAULT
)
{
Integer
currentIsolationLevel
=
TransactionSynchronizationManager
.
getCurrentTransactionIsolationLevel
();
...
...
spring-framework-main/spring-tx/src/main/java/org/springframework/transaction/support/DefaultTransactionStatus.java
View file @
f1543be3
...
...
@@ -61,6 +61,7 @@ public class DefaultTransactionStatus extends AbstractTransactionStatus {
private
final
boolean
debug
;
// 保存上层挂起的事务信息
@Nullable
private
final
Object
suspendedResources
;
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment