一、Spring声明式事务控制初探
声明式事务很⽅便,尤其纯注解模式,仅仅⼏个注解就能控制事务了
思 考 : 这 些 注 解 都 做 了 什 么 ? 好 神 奇 !
@EnableTransactionManagement @Transactional
1 @EnableTransactionManagement
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Import(TransactionManagementConfigurationSelector.class)public @interface EnableTransactionManagement {
@EnableTransactionManagement 注解使⽤ @Import 标签引⼊了
TransactionManagementConfigurationSelector类,这个类⼜向容器中导⼊了两个重要的组件:
AutoProxyRegistrar 和 ProxyTransactionManagementConfiguration。
@Overrideprotected String[] selectImports(AdviceMode adviceMode) {switch (adviceMode) {case PROXY:return new String[] {AutoProxyRegistrar.class.getName(),ProxyTransactionManagementConfiguration.class.getName()};case ASPECTJ:return new String[] {determineTransactionAspectClass()};default:return null;}}
selectImports方法来自org.springframework.context.annotation.ImportSelector
selectImports方法的返回String[]数组,这个数组存的是全限定类名,Spring会将这些全限定类名注入的容器中。
2 AutoProxyRegistrar组件
2.1 AutoProxyRegistrar#registerBeanDefinitions
AutoProxyRegistrar 类的 registerBeanDefinitions ⽅法中⼜注册了⼀个组件
该方法是对org.springframework.context.annotation.ImportBeanDefinitionRegistrar#registerBeanDefinitions接口方法的实现。
2.2 AopConfigUtils#registerAutoProxyCreatorIfNecessary
进⼊ AopConfigUtils.registerAutoProxyCreatorIfNecessary ⽅法
发现最终,注册了⼀个叫做 InfrastructureAdvisorAutoProxyCreator 的 Bean,⽽这个类是AbstractAutoProxyCreator 的⼦类,实现了 SmartInstantiationAwareBeanPostProcessor 接⼝
public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreatorpublic abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreatorpublic abstract class AbstractAutoProxyCreator extends ProxyProcessorSupportimplements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware
继承体系结构图如下
它实现了SmartInstantiationAwareBeanPostProcessor,说明这是⼀个后置处理器,⽽且跟spring AOP 开启@EnableAspectJAutoProxy 时注册的 AnnotationAwareAspectJProxyCreator实现的是同⼀个接⼝,所以说,声明式事务是 springAOP 思想的⼀种应⽤。
3 ProxyTransactionManagementConfiguration 组件
/*● Copyright 2002-2017 the original author or authors.*● Licensed under the Apache License, Version 2.0 (the "License");● you may not use this file except in compliance with the License.● You may obtain a copy of the License at*● https://www.apache.org/licenses/LICENSE-2.0*● Unless required by applicable law or agreed to in writing, software● distributed under the License is distributed on an "AS IS" BASIS,● WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied.● See the License for the specific language governing permissions and● limitations under the License.*/package org.springframework.transaction.annotation;import org.springframework.beans.factory.config.BeanDefinition;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Role;import org.springframework.transaction.config.TransactionManagementConfigUtils;import org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor;import org.springframework.transaction.interceptor.TransactionAttributeSource;import org.springframework.transaction.interceptor.TransactionInterceptor;/**● {@code @Configuration} class that registers the Spring infrastructure beans● necessary to enable proxy-based annotation-driven transaction management.*● @author Chris Beams● @since 3.1● @see EnableTransactionManagement● @see TransactionManagementConfigurationSelector*/ @Configurationpublic class ProxyTransactionManagementConfigurationextends AbstractTransactionManagementConfiguration {@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)@Role(BeanDefinition.ROLE_INFRASTRUCTURE)public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {// 事务增强器BeanFactoryTransactionAttributeSourceAdvisor advisor =new BeanFactoryTransactionAttributeSourceAdvisor();// 向事务增强器中注⼊属性解析器 transactionAttributeSourceadvisor.setTransactionAttributeSource(transactionAttributeSource());// 向事务增强器中注⼊ 事务拦截器 transactionInterceptoradvisor.setAdvice(transactionInterceptor());if (this.enableTx != null) {advisor.setOrder(this.enableTx.<Integer>getNumber("order"));}return advisor;}@Bean@Role(BeanDefinition.ROLE_INFRASTRUCTURE)// 属性解析器 transactionAttributeSourcepublic TransactionAttributeSource transactionAttributeSource() {return new AnnotationTransactionAttributeSource();}@Bean@Role(BeanDefinition.ROLE_INFRASTRUCTURE)// 事务拦截器 transactionInterceptorpublic TransactionInterceptor transactionInterceptor() {TransactionInterceptor interceptor = new TransactionInterceptor();interceptor.setTransactionAttributeSource(transactionAttributeSource());if (this.txManager != null) {interceptor.setTransactionManager(this.txManager);}return interceptor;}}
ProxyTransactionManagementConfiguration是⼀个容器配置类,注册了⼀个组件transactionAdvisor,称为事务增强器,然后在这个事务增强器中⼜注⼊了两个属性: 属性解析器transactionAttributeSource 和 事务拦截器transactionInterceptor
3.1 AnnotationTransactionAttributeSource 部分源码如下

属性解析器有⼀个成员变量是annotationParsers,是⼀个集合,可以添加多种注解解析器
(TransactionAnnotationParser),我们关注 Spring 的注解解析器,部分源码如下
3.2 TransactionAnnotationParser

属性解析器的作⽤之⼀就是⽤来解析@Transaction注解
3.3 TransactionInterceptor 事务拦截器


上述组件如何关联起来的?
- 事务拦截器实现了MethodInterceptor接⼝,追溯⼀下上⾯提到的InfrastructureAdvisorAutoProxyCreator后置处理器,它会在代理对象执⾏⽬标⽅法的时候获取其拦截器链,⽽拦截器链就是这个TransactionInterceptor,这就把这两个组件联系起来;
- 构造⽅法传⼊PlatformTransactionManager(事务管理器)、TransactionAttributeSource(属 性解析器),但是追溯⼀下上⾯贴的ProxyTransactionManagementConfiguration的源码, 在注册事务拦截器的时候并没有调⽤这个带参构造⽅法,⽽是调⽤的⽆参构造⽅法,然后再调⽤set⽅法注⼊这两个属性,效果⼀样。
3.4 invokeWithinTransaction方法
invokeWithinTransaction ⽅法,部分源码如下(关注1、2、3、4 标注处)

4 声明式事务分析课堂讲解过程中记录
@EnableTransactionManagement 注解
1) 通过@import引⼊了TransactionManagementConfigurationSelector类,
它的selectImports⽅法导⼊了另外两个类:AutoProxyRegistrar
和ProxyTransactionManagementConfiguration
2)AutoProxyRegistrar类分析
2.1) ⽅法registerBeanDefinitions中,引⼊了其他类,通过
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry)引⼊
InfrastructureAdvisorAutoProxyCreator,它继承了AbstractAutoProxyCreator,
是⼀个后置处理器类
3)ProxyTransactionManagementConfiguration
是⼀个添加了@Configuration注解的配置类(注册bean)
注册事务增强器(注⼊属性解析器、事务拦截器)
3.1) 属性解析器:AnnotationTransactionAttributeSource,内部持有了⼀个解析器集合
Set<TransactionAnnotationParser> annotationParsers;
具体使⽤的是SpringTransactionAnnotationParser解析器,⽤来解析@Transactional的事务属性
3.2) 事务拦截器:TransactionInterceptor实现了MethodInterceptor接⼝,
该通⽤拦截会在产⽣代理对象之前和aop增强合并,最终⼀起影响到代理对象
TransactionInterceptor的invoke⽅法中invokeWithinTransaction会触发原有业务逻辑调⽤
(增强事务)
