六Spring事务源码分析--7事务配置

六Spring事务源码分析--7事务配置

spring事务有声明式和非声明式事务,这里以声明式注解事务为例,分析源码实现。

image-20220519234917242

6.5.1 事务配置

image-20230310135631729

用@EnableTransactionManagement开启和配置事务。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
//导入事务管理配置器的选择器selector,用来根据proxy模式选择向beanFactory注册spring事务相关的核心组件
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
	//代理对象是类还是接口的类(用来确定使用jdk或者cglib的代理模式)
	boolean proxyTargetClass() default false;
	//代理模式,是proxy或者aspectj
	AdviceMode mode() default AdviceMode.PROXY;
	//当多个事务配置在一个特定的joinpoint时,确定事务的执行顺序
	int order() default Ordered.LOWEST_PRECEDENCE;
}

TransactionManagementConfigurationSelector.selectImports()返回字符串数组,通过Parser类,创建两个实例类---AutoProxyRegistrar、ProxyTransactionManagementConfiguration

public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {

	@Override
	protected String[] selectImports(AdviceMode adviceMode) {
		switch (adviceMode) {
                //返回两个类名称AutoProxyRegistrar、ProxyTransactionManagementConfiguration
			case PROXY: 
//TAG
				return new String[] {AutoProxyRegistrar.class.getName(),
						ProxyTransactionManagementConfiguration.class.getName()};
			case ASPECTJ:
				return new String[] {determineTransactionAspectClass()};
			default:
				return null;
		}
	}
}
TAG1 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;
			}
			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) {
          //注册autoProxyCreator类
					AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
					if ((Boolean) proxyTargetClass) {
						AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
						return;
					}
				}
			}
		}
	}

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

	@Nullable
	public static BeanDefinition registerAutoProxyCreatorIfNecessary(
			BeanDefinitionRegistry registry, @Nullable Object source) {
		//向spring注册InfrastructureAdvisorAutoProxyCreator类
		return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
	}

AutoProxyRegistrar类向spring注册事务的自动代理创建类InfrastructureAdvisorAutoProxyCreator。

InfrastructureAdvisorAutoProxyCreator提供isEligibleAdvisorBean(String beanName)方法判断当前beanname是否是符合条件的AdvisorBean。

只有ProxyTransactionManagementConfiguration配置类创建的advisor、advice和AnnotationTransactionAttributeSource为BeanDefinition.ROLE_INFRASTRUCTURE。因此该逻辑主要是筛查出这三个实例。

TAG2 ProxyTransactionManagementConfiguration

该类是spring事务的重要配置类,用来自动创建事务所需要的advisor等重要组件类。

//配置类
@Configuration(proxyBeanMethods = false)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

/**…………………………………………………………………………………………………创建spring事务的advisor类……………………………………………………………………………………*/
	@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(
			TransactionAttributeSource transactionAttributeSource, TransactionInterceptor transactionInterceptor) {
		//创建advisor类
		BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
    //设置属性源source
		advisor.setTransactionAttributeSource(transactionAttributeSource);
    //设置advice增强
		advisor.setAdvice(transactionInterceptor);
		if (this.enableTx != null) {
      //如果有顺序属性,设置优先级
			advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
		}
		return advisor;
	}

/**…………………………………………………………创建spring事务的AnnotationTransactionAttributeSource类…………………………………………………*/
	@Bean
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public TransactionAttributeSource transactionAttributeSource() {
    ///该类用来解析@Transactional注解上的事务属性
		return new AnnotationTransactionAttributeSource();
	}

/**…………………………………………………………………………………………………创建spring事务的advice类……………………………………………………………………………………*/
	@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;
	}

}

配置类,创建spring事务所需要的advisor、advice和AnnotationTransactionAttributeSource(用来解析@Transactional上的事务属性)。

总结:

@EnableTransactionManagement注解,自动创建spring事务所需要组件类:

	//自动代理创建类
InfrastructureAdvisorAutoProxyCreator;
  //Advisor类(包含advice、pointcut、transactionAttributeSource)
BeanFactoryTransactionAttributeSourceAdvisor;
  //解析事务属性(xml配置或@Transactional注解的方法)
TransactionAttributeSource;
  //Advice
TransactionInterceptor;
posted @ 2023-03-10 17:18  LeasonXue  阅读(45)  评论(0编辑  收藏  举报