Spring源碼分析筆記--事務管理

核心類

InfrastructureAdvisorAutoProxyCreator

本質是一個後置處理器,和AOP的後置處理器相似,但比AOP的使用級別低。當開啓AOP代理模式後,優先使用AOP的後置處理器。java

AopConfigUtils:spring

/**
 * The bean name of the internally managed auto-proxy creator.
 */
//和AOP同樣都向容器注入以此爲name的後置處理器,進行代理類的建立
public static final String AUTO_PROXY_CREATOR_BEAN_NAME =
      "org.springframework.aop.config.internalAutoProxyCreator";

/**
 * Stores the auto proxy creator classes in escalation order.
 */
//按升級的順序存儲進行代理類建立的後置處理器
private static final List<Class<?>> APC_PRIORITY_LIST = new ArrayList<Class<?>>();

/**
 * Setup the escalation list.
 */
//代理建立類後置處理器升級列表,下標越大等級越高
static {
   APC_PRIORITY_LIST.add(InfrastructureAdvisorAutoProxyCreator.class);
   APC_PRIORITY_LIST.add(AspectJAwareAdvisorAutoProxyCreator.class);
   APC_PRIORITY_LIST.add(AnnotationAwareAspectJAutoProxyCreator.class);
}

 

源碼跟蹤

查看註解@EnableTransactionManagement源碼,經過@Import導入TransactionManagementConfigurationSelector類,在類的重寫方法中能夠看到向容器注入了兩個類AutoProxyRegistrar、ProxyTransactionManagementConfigurationui

AutoProxyRegistrar

用於向容器中註冊事務管理用的後置處理器this

==》org.springframework.context.annotation.AutoProxyRegistrar#registerBeanDefinitionsspa

       AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);scala

==》org.springframework.aop.config.AopConfigUtils#registerAutoProxyCreatorIfNecessary(org.springframework.beans.factory.support.BeanDefinitionRegistry)代理

==》org.springframework.aop.config.AopConfigUtils#registerAutoProxyCreatorIfNecessary(org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object)code

==》org.springframework.aop.config.AopConfigUtils#registerOrEscalateApcAsRequiredorm

//此類下檢查容器中是否有name爲:"org.springframework.aop.config.internalAutoProxyCreator"的後置處理器bean,若是沒有則註冊,若是有則比較等級大小,如果等級大則對原beanDefination升級。例如:若是啓用了AOP則不用升級blog

 

ProxyTransactionManagementConfiguration

配置事務管理所需的管理器、參數等

@Configuration
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
//相似AOP,這裏建立了一個用於事務Advisor的Bean
   @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
      BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
      advisor.setTransactionAttributeSource(transactionAttributeSource());
      advisor.setAdvice(transactionInterceptor());
      advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
      return advisor;
   }
//封裝事務管理配置的參數,@Transactional(..)中的參數
   @Bean
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public TransactionAttributeSource transactionAttributeSource() {
      return new AnnotationTransactionAttributeSource();
   }
//封裝事務用的advice爲Interceptor,並關聯上了事務管理器
// TransactionInterceptor與AOP的Interceptor同樣都繼承自MethodInterceptor
//事務管理器主要用來控制事務,commit、rollback等
   @Bean
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public TransactionInterceptor transactionInterceptor() {
      TransactionInterceptor interceptor = new TransactionInterceptor();
      interceptor.setTransactionAttributeSource(transactionAttributeSource());
      if (this.txManager != null) {
         interceptor.setTransactionManager(this.txManager);
      }
      return interceptor;
   }

}

運行時源碼

運行時原理同AOP,對添加了@Transactional註解的類作代理,對被代理類的方法進行加強處理,執行一個攔截器鏈。跟蹤進去能夠發現Interceptor chain中多了一個TransactionIntercepor。經過此Interceptor在方法前開啓事務,在方法後commit或rollback。

TransactionInterceptor

==》org.springframework.transaction.interceptor.TransactionInterceptor#invoke

==》 org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction

// If the transaction attribute is null, the method is non-transactional.
//獲取事務相關屬性、管理器
final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass);
final PlatformTransactionManager tm = determineTransactionManager(txAttr);
final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);

if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
   // Standard transaction demarcation with getTransaction and commit/rollback calls.
//開啓一個事務
   TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
   Object retVal = null;
   try {
      // This is an around advice: Invoke the next interceptor in the chain.
      // This will normally result in a target object being invoked.
//調用被代理類的方法     
 retVal = invocation.proceedWithInvocation();
   }
   catch (Throwable ex) {
      // target invocation exception
    //回滾事務
      completeTransactionAfterThrowing(txInfo, ex);
      throw ex;
   }
   finally {
      cleanupTransactionInfo(txInfo);
   }
    //提交事務
   commitTransactionAfterReturning(txInfo);
   return retVal;
}

流程梳理

一、 建立後置處理器InfrastructureAdvisorAutoProxyCreator

二、 建立TransactionInterceptor,加入interceptor chain。

三、 對指定後置處理器爲InfrastructureAdvisorAutoProxyCreator的bean使用TransactionInterceptor進行事務處理。

相關文章
相關標籤/搜索