Hexo

点滴积累 豁达处之

0%

aop—事务源码分析

spring事物源码分析

事物概念解析

什么是事物?

事务是逻辑上的一组执行单元,要么都执行,要么都不执行.

事物的特性(ACID)

什么是ACID
** ACID是指数据库管理系统DBMS中事物所具有四个特性** eg:在数据库系统中,一个事务由一系列的数据库操作组成一个完整的逻辑过程,比如银行转账,从原账户扣除金额,目标账户增加金额

1:atomicity【原子性】

1
原子性表现为操作不能被分割,那么这二个操作 要么同时完成,要么就全部不完成,若事务出错了, 那么事务就会回滚, 好像什么 都 没有发生过 

2:Consistency【一致性】

1
一致性也比较容易理解,也就是说数据库要一直处于一致的状态,事务开始前是一个一致状态,事务结束后是另一个一致状态,事务将数据库从一个一致状态转移到另一个一致状态 

3:Isolation【隔离性】

1
所谓的独立性就是指并发的事务之间不会互相影响,如果一个事务要访问的数据正在被另外一个事务修改,只要另外一个事务还未提交,它所访问的数据就不受未提交事务的影响。换句话说,一个事务的影响在该事务提交前对其它事务是不可见的

4:Durability【持久性】

1
若事务已经提交了,那么就回在数据库中永久的保存下来 

事务三大接口介绍

2.1) PlatformTransactionManager: (平台)事务管理器
2.2) TransactionDefinition: 事务定义信息(事务隔离级别、传播行为、超时、只读、回滚规则 2.3)TransactionStatus: 事务运行状态

PlatformTransactionManager

Spring并不直接管理事务,而是提供了多种事务管理器 ,他们将事务管理的职责委托给Hibernate或者JTA等持
久化机制所提供的相关平台框架的事务来实现
Spring事务管理器的接口是:org.springframework.transaction.PlatformTransactionManager

通过这个接口,Spring为各个平台如JDBC、Hibernate等都提供了对应的事务管理器,但是具体的实现
就是各个平台自己的事情了。

1
2
3
4
5
6
7
8
public interface PlatformTransactionManager { 
/** 获取事物状态 */
TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException;
/** 事物提交 */
void commit(TransactionStatus status) throws TransactionException;
/** 事物回滚 */
void rollback(TransactionStatus status) throws TransactionException;
}

TransactionDefinition

事物属性的定义 : org.springframework.transaction.TransactionDefinition

TransactionDefinition接口中定义了5个方法以及一些表示事务属性的常量比如隔离级别、传播行为等等的常量。
我下面只是列出了TransactionDefinition接口中的方法而没有给出接口中定义的常量,该接口中的常量信息会在后面依次介绍到

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
public interface TransactionDefinition {
/**支持当前事物,若当前没有事物就创建一个事物 **/
int PROPAGATION_REQUIRED = 0;
/**如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行 **/
int PROPAGATION_SUPPORTS = 1;
/** 如果当前存在事务,则加入该事务;如果当前没有事务,则抛出异常*/
int PROPAGATION_MANDATORY = 2;
/** *创建一个新的事务,如果当前存在事务,则把当前事务挂起 **/
int PROPAGATION_REQUIRES_NEW = 3;
/**以非事务方式运行,如果当前存在事务,则把当前事务挂起 * */
int PROPAGATION_NOT_SUPPORTED = 4;
/**以非事务方式运行,如果当前存在事务,则抛出异常。 * */
int PROPAGATION_NEVER = 5;
/**
如果当前正有一个事务在运行中,则该方法应该运行在 一个嵌套的事务中,被嵌套的事务可以独立于封装事务 进行提交或者回滚(保存点), 如果封装事务不存在,行为就像 PROPAGATION_REQUIRES NEW
*/
int PROPAGATION_NESTED = 6;
/**
使用后端数据库默认的隔离级别,Mysql 默认采用的 REPEATABLE_READ隔离级别 Oracle
默认采用的 READ_COMMITTED隔离级别
*/
int ISOLATION_SERIALIZABLE = Connection.TRANSACTION_SERIALIZABLE;
/** *使用默认的超时时间*/
int TIMEOUT_DEFAULT = -1;

/** *获取事物的传播行为*/
int getPropagationBehavior();
/** *获取事物的隔离级别*/
int getIsolationLevel();
/** *返回事物的超时时间*/
int getTimeout();
/** *返回当前是否为只读事物*/
boolean isReadOnly();
/** *获取事物的名称 */
@Nullable
String getName();
}

Spring_tran04

TransactionStatus

TransactionStatus接口用来记录事务的状态 该接口定义了一组方法,用来获取或判断事务的相应状态信 息.

PlatformTransactionManager.getTransaction(…) 方法返回一个 TransactionStatus 对象。返回的 TransactionStatus 对象可能代表一个新的或已经存在的事务(如果在当前调用堆栈有一个符合条件的 事物

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface TransactionStatus extends SavepointManager, Flushable {
/**是否为新事物 * */
boolean isNewTransaction();
/** *是否有保存点*/
boolean hasSavepoint();
/** *设置为只回滚*/
void setRollbackOnly();
/** *是否为只回滚*/
boolean isRollbackOnly();
/** *属性*/
@Override void flush();
/** *判断当前事物是否已经完成*/
boolean isCompleted();
}

@EnableTransactionManagement

Spring_tran05

@EnableTransactionManagement接口

org.springframework.transaction.annotation.EnableTransactionManagement

1
2
3
4
5
6
7
8
9
10
11
12
13
@Target(ElementType.TYPE) 
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
/**
* 指定使用什么代理模式(true为cglib代理,false 为jdk代理) * */
boolean proxyTargetClass() default false;
/**
* 通知模式 是使用代理模式还是aspectj 我们一般使用Proxy * */
AdviceMode mode() default AdviceMode.PROXY;
int order() default Ordered.LOWEST_PRECEDENCE;
}

通过@Import导入了TransactionManagementConfigurationSelector组件

TransactionManagementConfigurationSelector源码分析

我们可以分析处向容器中导入了二个组件
1)AutoProxyRegistrar
2)ProxyTransactionManagementConfiguration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement>
/**
* 往容器中添加组件
* 1) AutoProxyRegistrar
* 2) ProxyTransactionManagementConfiguration
* */
@Override
protected String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) { //因为我们配置的默认模式是PROXY
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;
}
}
}

首先我们来分析AutoProxyRegistrar给我们容器中干了什么?

从源码分析出,AutoProxyRegistrar为我们容器注册了一个InfrastructureAdvisorAutoProxyCreator组件

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
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
private final Log logger = LogFactory.getLog(this.getClass());

public AutoProxyRegistrar() {
}

public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
boolean candidateFound = false;
//从我们传入进去的配置类上获取所有的注解的
Set<String> annoTypes = importingClassMetadata.getAnnotationTypes();
Iterator var5 = annoTypes.iterator();
//循环我们上一步获取的注解
while(var5.hasNext()) {
String annoType = (String)var5.next();
AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annoType);
if (candidate != null) {
//获取注解的mode属性
Object mode = candidate.get("mode");
//获取注解的proxyTargetClass
Object proxyTargetClass = candidate.get("proxyTargetClass");
//根据mode和proxyTargetClass的判断来注册不同的组件
if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() && Boolean.class == proxyTargetClass.getClass()) {
candidateFound = true;
if (mode == AdviceMode.PROXY) {
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
if ((Boolean)proxyTargetClass) {
AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
return;
}
}
}
}
}
if (!candidateFound && this.logger.isWarnEnabled()) {
String name = this.getClass().getSimpleName();
this.logger.warn(...);
}
}
}

public static BeanDefinition registerAutoProxyCreatorIfNecessary(
BeanDefinitionRegistry registry) {
return registerAutoProxyCreatorIfNecessary(registry, null);
}

public static BeanDefinition registerAutoProxyCreatorIfNecessary(
BeanDefinitionRegistry registry, Object source) {
return registerOrEscalateApcAsRequired(
InfrastructureAdvisorAutoProxyCreator.class, registry, source);
}

private static BeanDefinition registerOrEscalateApcAsRequired(
Class<?> cls, BeanDefinitionRegistry registry, Object source) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry.containsBeanDefinition(
"org.springframework.aop.config.internalAutoProxyCreator")) {
BeanDefinition apcDefinition = registry.getBeanDefinition(
"org.springframework.aop.config.internalAutoProxyCreator");
if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
int currentPriority = findPriorityForClass(
apcDefinition.getBeanClassName());
int requiredPriority = findPriorityForClass(cls);
if (currentPriority < requiredPriority) {
apcDefinition.setBeanClassName(cls.getName());
}
}

return null;
} else {
RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", -2147483648);
beanDefinition.setRole(2);
registry.registerBeanDefinition(
"org.springframework.aop.config.internalAutoProxyCreator",
beanDefinition);
return beanDefinition;
}
}

AutoProxyRegistrar会为我们容器中导入了一个叫InfrastructureAdvisorAutoProxyCreator的组件

1:我们来看下InfrastructureAdvisorAutoProxyCreator继承图,

Spring_tran06

我们来分析InfrastructureAdvisorAutoProxyCreator 实现了如下的接口

1:实现了Aware接口(具体代表 BeanFactoryAware接口)

做了什么事情)

a:把我们的BeanFacotry容器设置到了InfrastructureAdvisorAutoProxyCreator组件中去
b:创建了一个advisorRetrievalHelper组件 增强器检索工具

AbstractAutoProxyCreator 实现了BeanFactoryAware接口,但是马上又被AbstractAdvisorAutoProxyCreator给重写了;

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
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator 
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}

马上又被org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator重写了
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
throw new IllegalArgumentException(" + beanFactory);
}
initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
}

protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
this.advisorRetrievalHelper = new
BeanFactoryAdvisorRetrievalHelperAdapter(beanFactory);
}

但是AbstractAdvisorAutoProxyCreator类的initBeanFactory
又被InfrastructureAdvisorAutoProxyCreator重写了 org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator
protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
super.initBeanFactory(beanFactory);
this.beanFactory = beanFactory;
}

2:实现了我们的接口 InstantiationAwareBeanPostProcessor类型的后置处理器,为我们容器中做了
什么事情

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation
postProcessBeforeInstantiation方法

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
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = this.getCacheKey(beanClass, beanName);
if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}

if (this.isInfrastructureClass(beanClass) ||
this.shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}

if (beanName != null) {
TargetSource targetSource = this.getCustomTargetSource(
beanClass, beanName);
if (targetSource != null) {
this.targetSourcedBeans.add(beanName);
Object[] specificInterceptors =
this.getAdvicesAndAdvisorsForBean(
beanClass, beanName, targetSource);
Object proxy = this.createProxy(beanClass, beanName,
specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
}

return null;
}

postProcessAfterInstantiation方法(没有做任何事情,直接返回)

1
2
3
public boolean postProcessAfterInstantiation(Object bean, String beanName) { 
return true;
}

3:实现了我们的接口BeanPostProcessor类型的后置处理器,为我们容器中做了什么事情

postProcessBeforeInitialization方法没有做任何事情,直接返回

1
2
3
public Object postProcessBeforeInitialization(Object bean, String beanName) { 
return bean;
}

postProcessAfterInitialization 为我们做了事情

1
2
3
4
5
6
7
8
public Object postProcessAfterInitialization(Object bean, String beanName) 
throws BeansException { if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
return wrapIfNecessary(bean, beanName, cacheKey); }
}
return bean;
}

然后我们在来分析一下
TransactionManagementConfigurationSelector 为我们还导入了一个类
ProxyTransactionManagementConfiguration

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
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
public ProxyTransactionManagementConfiguration() {
}

/**
* 为我我们容器中导入了 beanName为
org.springframework.transaction.config.internalTransactionAdvisor
* 类型为:BeanFactoryTransactionAttributeSourceAdvisor 的增强器
* */
@Bean(
name = {"org.springframework.transaction.config.internalTransactionAdvisor"}
)
@Role(2)
public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
//设置了事物源属性对象
advisor.setTransactionAttributeSource(this.transactionAttributeSource());
//设置了事物拦截器对象
advisor.setAdvice(this.transactionInterceptor());
advisor.setOrder((Integer)this.enableTx.getNumber("order"));
return advisor;
}

/*** 定义了一个事物属性源对象 * */
@Bean
@Role(2)
public TransactionAttributeSource transactionAttributeSource() {
return new AnnotationTransactionAttributeSource();
}

/** 事物拦截器对象 **/
@Bean
@Role(2)
public TransactionInterceptor transactionInterceptor() {
TransactionInterceptor interceptor = new TransactionInterceptor();
//把事物属性源对象设置到我们的事物拦截器对象中
interceptor.setTransactionAttributeSource(this.transactionAttributeSource());
//把我们容器中的 事物对象配置到事物拦截器中
if (this.txManager != null) {
interceptor.setTransactionManager(this.txManager);
}
return interceptor;
}
}

Spring_tran07

Spring_tran08

上诉我们画图总结,下面再将具体的源码分析

Spring_tran09

流程图分析

Spring_tran02

源码解析

创建源代码过程

我们知道上图分析出,事物创建代理对象最最最主要的是InfrastructureAdvisorAutoProxyCreator这个类型

作为
后置处理器为我们创建代理对象,实际上是他的父类AbstractAutoProxyCreator实现了 postProcessBeforeInstantiation这个接口 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation 我们分析代码得出,再InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation没有为我们做了什 么事情,那么是怎么创建代理对象的了???

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
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = this.getCacheKey(beanClass, beanName);
//判断我们的beanName以及是否处理过
if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
/*
*判断当前的bean是不是基础的bean或者直接跳过,不需要代理的
advice
Pointcut
Advisor AopInfrastructureBean
**/
if (this.isInfrastructureClass(beanClass) ||
this.shouldSkip(beanClass, beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}

/**
* 判断我们容器中有没有自定义的targetSource 有为我们自动创建对象
* 当时这一步的要求比较高,而且我们正常不会这里创建对象 ...
* */
if (beanName != null) {
TargetSource targetSource = this.getCustomTargetSource(beanClass,
beanName);
if (targetSource != null) {
this.targetSourcedBeans.add(beanName);
Object[] specificInterceptors =
this.getAdvicesAndAdvisorsForBean(beanClass, beanName,
targetSource);
Object proxy = this.createProxy(beanClass, beanName,
specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
}

return null;
}

protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
//容器中必须要包含有个TargetSourceCreators 并且我们的组件也需要实现TargetSource接口
if (this.customTargetSourceCreators != null && this.beanFactory != null &&
this.beanFactory.containsBean(beanName)) {
TargetSourceCreator[] var3 = this.customTargetSourceCreators;
int var4 = var3.length;

for(int var5 = 0; var5 < var4; ++var5) {
TargetSourceCreator tsc = var3[var5];
TargetSource ts = tsc.getTargetSource(beanClass, beanName);
if (ts != null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug(...)
}

return ts;
}
}
}

return null;
}

我们知道上图分析出,事物创建代理对象最最最主要的是InfrastructureAdvisorAutoProxyCreator这个类型作为
后置处理器为我们创建代理对象,实际上是他的父类AbstractAutoProxyCreator实现了 postProcessAfterInitialization这个接口
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization

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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
    public Object postProcessAfterInitialization(Object bean, String beanName) 
throws BeansException { if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
//当前对象是否需要包装
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { //判断代理对象再postProcessAfterInitialization接口中是否被处理过
if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
return bean;
}

if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
return bean;
}
//是否为基础的Bean 或者该对象不应该被调用
if (isInfrastructureClass(bean.getClass()) ||
shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}

//找到我们容器中所有的增强器
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(),
beanName, null);
//增强器不为空
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE); //创建代理对象
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new
SingletonTargetSource(bean)); this.proxyTypes.put(cacheKey,
proxy.getClass());
return proxy;
}

this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
)
org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator#getAdvicesAndAdvisorsForBean(AbstractAuto protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName,
TargetSource targetSource) {
//找到合适的增强器
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
//增强器为空,不需要代理
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
//返回增强器
return advisors.toArray();
}

/* *找到合适的增强器 **/
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String
beanName) {
//找到候选的增强器
List<Advisor> candidateAdvisors = findCandidateAdvisors();
//从候选的中挑选出合适的增强器
List<Advisor> eligibleAdvisors =
findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
//增强器进行扩展
extendAdvisors(eligibleAdvisors);
//对增强器进行排序
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}

=======================findCandidateAdvisors();=====================
/**
* 找到候选的增强器
* */
protected List<Advisor> findCandidateAdvisors() {
//通过我们我们增强器探测工具找
return this.advisorRetrievalHelper.findAdvisorBeans();
}
org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper#findAdvisorBeans

public List<Advisor> findAdvisorBeans() {
//看我们类级别缓存中有没有
String[] advisorNames = this.cachedAdvisorBeanNames;
if (advisorNames == null) {
//去容器中查找实现了我们Advisor接口的实现类 的名称:
//(org.springframework.transaction.config.internalTransactionAd
advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this.beanFactory, Advisor.class, true, false);
//放入到缓存中
this.cachedAdvisorBeanNames = advisorNames;
}
if (advisorNames.length == 0) {
return new ArrayList<Advisor>();
}

List<Advisor> advisors = new ArrayList<Advisor>(); //循环我们的增强器
for (String name : advisorNames) {
//判断是不是合适的
if (isEligibleBean(name)) {
//当前的增强器是不是正在创建的
if (this.beanFactory.isCurrentlyInCreation(name)) {
}
else {
try {
//通过getBean的显示调用获取
// BeanFactoryTransactionAttributeSourceAdvisor 组件
advisors.add(this.beanFactory.getBean(name, Advisor.class));
}
catch (BeanCreationException ex) {...
}
}
}
}
return advisors;
}

/**
* 判断包含是否为合适的最终逻辑
* 容器中的bean定义包含当前的增强器的bean定义,且
bean的role是int ROLE_INFRASTRUCTURE = 2; * */
protected boolean isEligibleAdvisorBean(String beanName) {
return (this.beanFactory.containsBeanDefinition(beanName) &&
this.beanFactory.getBeanDefinition(beanName).getRole() ==
BeanDefinition.ROLE_INFRASTRUCTURE);
}

=========================== findAdvisorsThatCanApply=======
protected List<Advisor> findAdvisorsThatCanApply(
List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
ProxyCreationContext.setCurrentProxiedBeanName(beanName);
try {
//真正的去候选的增强器中找到当前能用的增强器
return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
}
finally {
ProxyCreationContext.setCurrentProxiedBeanName(null); }
}

org.springframework.aop.support.AopUtils#findAdvisorsThatCanApply
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor>
candidateAdvisors, Class<?> clazz) {
//若传入进来的候选增强器为空直接返回
if (candidateAdvisors.isEmpty()) {
return candidateAdvisors;
}

//创建一个本类能用的增前期集合
List<Advisor> eligibleAdvisors = new LinkedList<Advisor>();

//循环候选的增强器
for (Advisor candidate : candidateAdvisors) {
//判断增强器是不是实现了IntroductionAdvisor 很明显没实现该接口
if (candidate instanceof IntroductionAdvisor &&
canApply(candidate, clazz)) {
eligibleAdvisors.add(candidate);
}
}

boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
if (candidate instanceof IntroductionAdvisor) {
// already processed
continue;
}
//正在找出能用的增强器
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}
return eligibleAdvisors;
}


/**
* 判断当前增强器是否为本来能用的 * */
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean
hasIntroductions) {
//根据类的继承图 发现 BeanFactoryTransactionAttributeSourceAdvisor
//没实现IntroductionAdvisor接口
if (advisor instanceof IntroductionAdvisor) {
return ((IntroductionAdvisor)
advisor).getClassFilter().matches(targetClass);
}
//BeanFactoryTransactionAttributeSourceAdvisor实现了PointcutAdvisor接口
else if (advisor instanceof PointcutAdvisor) {
//强制转换为PointcutAdvisor
PointcutAdvisor pca = (PointcutAdvisor) advisor;
return canApply(pca.getPointcut(), targetClass, hasIntroductions);
}
else {
// It doesn't have a pointcut so we assume it applies.
return true;
}
}

/** 判断当前增强器是否为本来能用的* */
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean
hasIntroductions) {
Assert.notNull(pc, "Pointcut must not be null");
if (!pc.getClassFilter().matches(targetClass)) {
return false;
}

/**
* 获取切点中的方法匹配器 TransactionAttributeSourcePointcut
* 该切点在创建BeanFactoryTransactionAttributeSourceAdvisor的时候
创建了切点TransactionAttributeSourcePointcut
**/
MethodMatcher methodMatcher = pc.getMethodMatcher();
if (methodMatcher == MethodMatcher.TRUE) {
// No need to iterate the methods if we're matching any method anyway...
return true;
}

/*** 判断方法匹配器是不是IntroductionAwareMethodMatcher*/
IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher)
methodMatcher;
}

//获取当前类的实现接口类型
Set<Class<?>> classes = new LinkedHashSet<Class<?>>
(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
classes.add(targetClass);
//循环上一步的接口类型
for (Class<?> clazz : classes) {
//获取接口的所有方法
Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
//循环我们接口中的方法
for (Method method : methods) {
//正在进行匹配的是methodMatcher.matches(method, targetClass)这个逻辑
if ((introductionAwareMethodMatcher != null
&&introductionAwareMethodMatcher.matches(method, targetC
methodMatcher.matches(method, targetClass)) {
return true;
}
}
}
return false;
}
org.springframework.transaction.interceptor.TransactionAttributeSourcePointcut#matches
public boolean matches(Method method, Class<?> targetClass) {
if (targetClass != null &&
TransactionalProxy.class.isAssignableFrom(targetClass)) {
return false;
}
//获取我们的事物源对象(在ProxyTransactionManagementConfiguration配置类配置的这里获取)
TransactionAttributeSource tas = getTransactionAttributeSource();
//从事物源对象中获取事物属性
return (tas == null || tas.getTransactionAttribute(method, targetClass) !=
null);
}

/**获取事物属性对象 **/
public TransactionAttribute getTransactionAttribute(Method method, Class<?>
targetClass) {
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);
}
//加入到缓存
this.attributeCache.put(cacheKey, txAttr);
}
return txAttr;
}
}

/**计算事物属性 * */
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?>
targetClass) {
//判断方法的修饰夫
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}

//忽略cglib的代理
Class<?> userClass = ClassUtils.getUserClass(targetClass);
/**
* method为接口中的方法,specificMethod为我们实现类方法
* */
Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
// 找我们【实现类】中的【方法】上的事物属性
TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
if (txAttr != null) {
return txAttr;
}

//【方法所在类】上有没有事物属性
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);
if (txAttr != null) {
return txAttr;
}

接口上】
txAttr = findTransactionAttribute(method.getDeclaringClass());
if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
return txAttr;
}
}
return null;
}

/**从方法上找事物属性对象 * */
protected TransactionAttribute findTransactionAttribute(Method method) {
return determineTransactionAttribute(method);
}

protected TransactionAttribute determineTransactionAttribute(AnnotatedElement
element) {
//获取方法上的注解
if (element.getAnnotations().length > 0) {
//事物注解解析器
for (TransactionAnnotationParser annotationParser :
this.annotationParsers) {
//解析我们的注解
TransactionAttribute attr =
annotationParser.parseTransactionAnnotation(element);
if (attr != null) {
return attr; }
}
}
return null;
}

/** 解析事物注解 * */
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
//解析@Transactional属性对象
AnnotationAttributes attributes =
AnnotatedElementUtils.getMergedAnnotationAttributes(
element, Transactional.class);
if (attributes != null) {
//真正的解析@Transactional属性
return parseTransactionAnnotation(attributes);
}
else {
return null;
}
}

/**解析事物注解 * */
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<RollbackRuleAttribute>();
//事物回滚规则
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;
}

真正的创建代理对象

org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createPr

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
protected Object createProxy(Class<?> beanClass, String beanName, Object[] 
specificInterceptors, TargetSource targetSource) {

//暴露代理对象
if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory)
this.beanFactory, beanName, beanClass);
}

//创建代理工厂
ProxyFactory proxyFactory = new ProxyFactory();
proxyFactory.copyFrom(this);

//判断是cglib代理还是jdk代理
if (!proxyFactory.isProxyTargetClass()) {
if (shouldProxyTargetClass(beanClass, beanName)) {
proxyFactory.setProxyTargetClass(true);
}
else {
evaluateProxyInterfaces(beanClass, proxyFactory);
}
}

//把合适的拦截器转为增强器
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
proxyFactory.addAdvisors(advisors); proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
//真正的创建代理对象
return proxyFactory.getProxy(getProxyClassLoader());
}

public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() ||
hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
//标识的是接口或者
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
//创建cglib接口
return new ObjenesisCglibAopProxy(config);
}
else { 创建jdk代理
return new JdkDynamicAopProxy(config);
}
}

public Object getProxy(ClassLoader classLoader) {
if (logger.isDebugEnabled()) {
logger.debug("Creating JDK dynamic proxy: target source is " +
this.advised.getTargetSource());
}
Class<?>[] proxiedInterfaces =
AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
}

代理对象调用流程

5.1)org.springframework.aop.framework.JdkDynamicAopProxy#invoke

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
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Class<?> targetClass = null;
Object target = null;

Object retVal;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
Boolean var20 = this.equals(args[0]);
return var20;
}

if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
Integer var18 = this.hashCode();
return var18;
}

if (method.getDeclaringClass() == DecoratingProxy.class) {
Class var17 = AopProxyUtils.ultimateTargetClass(this.advised);
return var17;
}

if (this.advised.opaque || !method.getDeclaringClass().isInterface() ||
!method.getDeclaringClass().isAssignableFrom(Advised.class)) {
//暴露代理对象
if (this.advised.exposeProxy) {
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}

target = targetSource.getTarget();
if (target != null) {
targetClass = target.getClass();
}
//把增强器转为方法拦截器链条
List<Object> chain =
this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
//拦截器链为空,直接通过反射进行调用
if (chain.isEmpty()) {
//通过反射进行调用
Object[] argsToUse =
AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method,
argsToUse);
} else {
//创建反射方法调用对象
MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
//通过方法拦截器进行拦截调用
retVal = invocation.proceed();
}

Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target && returnType != Object.class &&
returnType.isInstance(proxy) && !RawTargetAccess.class.
isAssignableFrom(method.getDeclaringClass())) {
retVal = proxy;
} else if (retVal == null && returnType != Void.TYPE &&
returnType.isPrimitive()) {
throw new AopInvocationException("" + method);
}

Object var13 = retVal;
return var13;
}

retVal = AopUtils.invokeJoinpointUsingReflection(this.advised, method,
args);
} finally {
if (target != null && !targetSource.isStatic()) {
targetSource.releaseTarget(target);
}

if (setProxyContext) {
AopContext.setCurrentProxy(oldProxy);
}

}

return retVal;
}

org.springframework.aop.framework.ReflectiveMethodInvocation#proceed

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
public Object proceed() throws Throwable {
//当前下标从-1开始,若当前索引值=执行到最后一个拦截器的下标,就执行目标方法
if (this.currentInterceptorIndex ==
this.interceptorsAndDynamicMethodMatchers.size() - 1) {
return this.invokeJoinpoint();
} else {
//获取我们的方法拦截器(TransactionInterceptor)
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.
get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof
InterceptorAndDynamicMethodMatcher) {
InterceptorAndDynamicMethodMatcher dm =
(InterceptorAndDynamicMethodMatcher)
interceptorOrInterceptionAdvice;
return dm.methodMatcher.matches(this.method, this.targetClass,
this.arguments) ? dm.interceptor.invoke(this) :
this.proceed();
} else {
//事务拦截器进行调用
return ((MethodInterceptor)interceptorOrInterceptionAdvice).
invoke(this);
}
}
}

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

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

org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction 事物调用)

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
protected Object invokeWithinTransaction(Method method, Class<?> targetClass, final
TransactionAspectSupport.InvocationCallback invocation) throws Throwable {
//通过@EnableTransactionManager 到入了TransactionAttributeSource 可以获取出事务属性对象
final TransactionAttribute txAttr =
this.getTransactionAttributeSource().getTransactionAttribute(method,
targetClass);
//获取工程中的事务管理器
final PlatformTransactionManager tm = this.determineTransactionManager(txAttr);
//获取我们需要切入的方法(也就是我们标识了@Transactional注解的方法)
final String joinpointIdentification = this.methodIdentification(method,
targetClass, txAttr);
Object result;
//再这里我们只看我们常用的事务管理器,很明显我们不会配置
// CallbackPreferringPlatformTransactionManager事务管理器
if (txAttr != null && tm instanceof
CallbackPreferringPlatformTransactionManager) {
//判断有没有必要开启事务
final TransactionAspectSupport.ThrowableHolder throwableHolder = new
TransactionAspectSupport.ThrowableHolder(null);
try {
result = ((CallbackPreferringPlatformTransactionManager)tm).
execute(txAttr, new TransactionCallback<Object>() {
public Object doInTransaction(TransactionStatus status) {
TransactionAspectSupport.TransactionInfo txInfo =
TransactionAspectSupport.this.prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);

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

throw new TransactionAspectSupport.
ThrowableHolderException(var8);
}

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

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

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

throw var20;
}
} else {
TransactionAspectSupport.TransactionInfo txInfo =
this.createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
result = null;

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

org.springframework.transaction.interceptor.TransactionAspectSupport#createTransactionIfNecessary

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

TransactionStatus status = null;
//获取一个事务状态
if (txAttr != null) {
if (tm != null) {
status = tm.getTransaction((TransactionDefinition)txAttr);
} else if (this.logger.isDebugEnabled()) {
this.logger.debug("" + joinpointIdentification + "");
}
}

//准备事务信息
return this.prepareTransactionInfo(tm, (TransactionAttribute)txAttr,
joinpointIdentification, status);
}

org.springframework.transaction.support.AbstractPlatformTransactionManager#getTransaction

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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
public final TransactionStatus getTransaction(TransactionDefinition definition) throws 
TransactionException {
//1:)先去尝试开启一个事务
Object transaction = this.doGetTransaction();
boolean debugEnabled = this.logger.isDebugEnabled();
//传入进来的事务定义为空
if (definition == null) {
//使用系统默认的
definition = new DefaultTransactionDefinition();
}
//2:)//判断是否存在事务(若存在事务,在这边直接返回不走下面的处理了)
if (this.isExistingTransaction(transaction)) {
return this.handleExistingTransaction((TransactionDefinition)definition,
transaction, debugEnabled);
// 3:)判读事务超时
} else if (((TransactionDefinition)definition).getTimeout() < -1) {
//不存在事务,需要在这边判断(PROPAGATION_MANDATORY 标识要求当前允许的在事务中,
// 但是第二步进行判断之后 说明这里
} else if (((TransactionDefinition)definition).getPropagationBehavior() == 2) {
throw new IllegalTransactionStateException("");
} else if (((TransactionDefinition)definition).getPropagationBehavior() != 0 &&
((TransactionDefinition)definition).getPropagationBehavior() != 3 &&
((TransactionDefinition)definition).getPropagationBehavior() != 6) {
if (((TransactionDefinition)definition).getIsolationLevel() != -1 &&
this.logger.isWarnEnabled()) {
this.logger.warn(" " + definition);
}

boolean newSynchronization = this.getTransactionSynchronization() == 0;
return this.prepareTransactionStatus((TransactionDefinition)definition,
(Object)null, true, newSynchronization, debugEnabled, (Object)null);
} else {
//挂起当前事务,但是当前是没有事务的
AbstractPlatformTransactionManager.SuspendedResourcesHolder
suspendedResources = this.suspend((Object)null);
if (debugEnabled) {
}

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

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

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

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

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

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

} catch (Throwable var7) {
if (txObject.isNewConnectionHolder()) {
//抛出异常,释放资源
DataSourceUtils.releaseConnection(con, this.dataSource);
txObject.setConnectionHolder((ConnectionHolder)null, false);
}

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

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

}

========= //准备事务信息 prepareTransactionInfo(tm, txAttr, joinpointIdentifi
protected TransactionAspectSupport.TransactionInfo prepareTransactionInfo(
PlatformTransactionManager tm, TransactionAttribute txAttr, String
joinpointIdentification, TransactionStatus status) {
//把事务管理器,事务属性,连接点信息封装成为TransactionInfo
TransactionAspectSupport.TransactionInfo txInfo = new TransactionAspectSupport.TransactionInfo(tm, txAttr, joinpointIdentification);
if (txAttr != null) {
//设置事务状态
txInfo.newTransactionStatus(status);
} else if (this.logger.isTraceEnabled()) {
}
//把事务信息绑定到当前线程上去
txInfo.bindToThread();
return txInfo;
}