文档章节

Spring5.0源码深度解析之SpringBean声明事务底层实现原理

须臾之余
 须臾之余
发布于 07/31 15:02
字数 2315
阅读 14
收藏 0

Spring事务

Spring声明式事务让我们从复杂的事务处理中得到解脱,使我们再也不用去处理这些步骤:获得连接、关闭连接、事务提交和回滚操作。再也不需要在事务相关方法中处理大量的try..catch..finally代码。

Spring中事务的使用虽然已经相对简单的多,但是,还是有很多的使用和配置规则,下面我们开始我们本章重点。

SpringAop基本原理和思想

1、事务保证数据一致性问题,只需要加上@Transactional

2、纯手写SpringAop环绕通知+手动事务就可以声明事务

基于Spring注解方式构建整合JDBC环境

@Repository
public class OrderDao {
    @Autowired()
    private JdbcTemplate jdbcTemplate;
    public void addOrder() {
        jdbcTemplate.update("insert into order_info values(null,'mayikt','zhangsan','1111')");
    }
}
@Configuration
@ComponentScan("com.mayikt")
@EnableTransactionManagement//开启事务注解
public class MyConfig {
    //注入到ioc容器中 beanid =dataSource class=DataSource类的完整路径地址
    // 配置我们的数据源
    @Bean
    public DataSource dataSource() {
        MysqlDataSource mysqlDataSource = new MysqlDataSource();
        mysqlDataSource.setUser("root");
        mysqlDataSource.setPassword("root");
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8");
        mysqlDataSource.setDatabaseName("test");
        return mysqlDataSource;
    }
    /**
     * 注入JdbcTemplate
     */
    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }
    @Bean
    public PlatformTransactionManager platformTransactionManager(){
         return  new DataSourceTransactionManager(dataSource());
    }
}
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Transactional//开启事务
    public void addOrder() {
        try {
            orderDao.addOrder();
            int i = 1 / 0; // 如果报错的情况下肯定是会插入到数据库中
        } catch (Exception e) {
        }
    }
}
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>

    <!-- mysql 依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.46</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.0.5.RELEASE</version>
    </dependency>
</dependencies>

Spring声明事务底层源码分析

@EnableTransactionManagement//开启事务
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
TransactionManagementConfigurationSelector的祖宗是ImportSelector

public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {

   @Override
   protected String[] selectImports(AdviceMode adviceMode) {
      switch (adviceMode) {
         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;
      }
   }

}
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {//向IOC容器中注入Bean对象
 ....
   @Override
   public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    ....
         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;
               }
            }
         }
      }
     ....
}
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
    return registerAutoProxyCreatorIfNecessary(registry, (Object)null);
}
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, @Nullable Object source) {
    return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
}

将InfrastructureAdvisorAutoProxyCreator注入到IOC容器中:

InfrastructureAdvisorAutoProxyCreator的类图如下:祖宗是BeanPostProcessor后置处理器,父类是AbstractAutoProxyCreater

回到registerOrEscalateApcAsRequired方法:beanid为:internalAutoProxyCreator,value为:InfrastructureAdvisorAutoProxyCreator对象

private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, @Nullable 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;
    }
}

下面回到ProxyTransactionManagementConfiguration方法

protected String[] selectImports(AdviceMode adviceMode) {
   switch (adviceMode) {
      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;
   }
}
@Configuration
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

   @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
   @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
   public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
      BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
      advisor.setTransactionAttributeSource(transactionAttributeSource());
      advisor.setAdvice(transactionInterceptor());
      if (this.enableTx != null) {
         advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
      }
      return advisor;
   }

BeanId:transactionInterceptor;value为:TransactionInterceptor这个对象

打印所有注册的Bean

org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
myConfig
orderDao
orderServiceImpl
org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration
org.springframework.transaction.config.internalTransactionAdvisor
transactionAttributeSource
transactionInterceptor【】【】【】【】这里
org.springframework.transaction.config.internalTransactionalEventListenerFactory
dataSource
jdbcTemplate
platformTransactionManager
org.springframework.aop.config.internalAutoProxyCreator【】【】【】【】这里
 

加上@EnableTransactionManagement这个注解将 :TransactionInterceptor,和InternalAutoProxyCreator这两个类注入到IOC容器中

下面重点分析这两个类transactionInterceptor】,【internalAutoProxyCreator

从上面类结构可知:InfrastructureAdvisorAutoProxyCreator间接实现了SmartInstantiationAwareBeanPostProcessor,而SmartInstantiationAwareBeanPostProcessor又继承自

InstantiationAwareBeanPostProcessor,也就是说在Spring中,所有的bean实例化时Spring都会保证调用其postProcessAfterInstantiation方法,其实现是在父类AbstractAutoProxyCreater中实现的。

我们一旦把这个类:InfrastructureAdvisorAutoProxyCreator注入到容器中,Bean对象在初始化时,会判断是否需要创建代理类。

进入AbstractAutoProxyCreater的后置处理器:

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) throws BeansException {
    if (bean != null) {
        //根据给定的bean的class和name构建出key,beanClassName_beanName
        Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
        //是否是由于避免循环依赖而创建bean的代理
        if (!this.earlyProxyReferences.contains(cacheKey)) {
            return this.wrapIfNecessary(bean, beanName, cacheKey);
        }
    }
    return bean;
}

这里实现的主要目的是针对指定的bean进行封装,当然首先要确定是否需要封装,检测及封装的工作都委托给了wrapIfNecessary函数进行。

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    //如果已经处理过
    if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
        return bean;
    } else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
        return bean;
    } else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) {
        Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null);
        if (specificInterceptors != DO_NOT_PROXY) {
            this.advisedBeans.put(cacheKey, Boolean.TRUE);
            Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));//关键点,创建代理,对需要增强的bean创建代理(CGLIBProxy或者JDKProxy)
            this.proxyTypes.put(cacheKey, proxy.getClass());
            return proxy;
        } else {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }
    } else {
        this.advisedBeans.put(cacheKey, Boolean.FALSE);
        return bean;
    }
}

wrapIfNecessary函数功能实现起来很复杂,但是逻辑上还是相对简单,在wrapIfNecessary函数中主要做了以下工作:

  1. 找出指定bean对应的增强器【上篇文章详细介绍了,异曲同工】
  2. 根据找出的增强器创建代理【上篇文章详细介绍了,异曲同工】

下面简单浏览下:

protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
    List<Advisor> advisors = this.findEligibleAdvisors(beanClass, beanName);
    return advisors.isEmpty() ? DO_NOT_PROXY : advisors.toArray();
}
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
    List<Advisor> candidateAdvisors = this.findCandidateAdvisors();//寻找候选增强器,这里不介绍了
    List<Advisor> eligibleAdvisors = this.findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);//候选增强器中寻找匹配项,这里分析下
  ....
}
protected List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
 ....
    try {
        var4 = AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
....
}
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
 ....
        while(var3.hasNext()) {
            Advisor candidate = (Advisor)var3.next();
            //首先处理引介增强
            if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
                eligibleAdvisors.add(candidate);
            }
        }
....
        while(var7.hasNext()) {
            Advisor candidate = (Advisor)var7.next();
            //对普通bean的处理
            if (!(candidate instanceof IntroductionAdvisor) && canApply(candidate, clazz, hasIntroductions)) {
                eligibleAdvisors.add(candidate);
            }
....
    }
}
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
    if (advisor instanceof IntroductionAdvisor) {
        return ((IntroductionAdvisor)advisor).getClassFilter().matches(targetClass);
    } else if (advisor instanceof PointcutAdvisor) {
        PointcutAdvisor pca = (PointcutAdvisor)advisor;
        return canApply(pca.getPointcut(), targetClass, hasIntroductions);
    } else {
        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;
    } else {
        MethodMatcher methodMatcher = pc.getMethodMatcher();
      ....
                for(int var11 = 0; var11 < var10; ++var11) {
                    Method method = var9[var11];
                    if (introductionAwareMethodMatcher != null && introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) || methodMatcher.matches(method, targetClass)) {
                        return true;
....
        }
    }
}
public boolean matches(Method method, @Nullable Class<?> targetClass) {
....
    //自定义标签解析时注入
   TransactionAttributeSource tas = getTransactionAttributeSource();
   return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}
public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
....
   else {
      // We need to work it out.
      TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
  ....
}
protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
....
   //method代表接口中的方法,specificMethod代表实现类中的方法
   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);
      if (txAttr != null) {
         return txAttr;
      }
      // Last fallback is the class of the original method.
      txAttr = findTransactionAttribute(method.getDeclaringClass());
      if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
         return txAttr;
      }
   }

   return null;
}

对于事务属性的获取规则相信大家都已经很清楚了,如果方法中存在事务属性,则使用方法上的属性,否则使用方法所在类上的属性,如果方法所在类的属性上还是没有搜寻到对应的事务属性,那么再搜寻接口中的方法,再没有的化,

最好尝试搜寻接口的类上面的声明。对于函数computeTransactionAttribute中的逻辑,就是搭建了一个执行框架而已,将搜寻事务属性任务委托给了findTransactionAttribute方法去执行。下面看看这个方法。

protected TransactionAttribute findTransactionAttribute(Method method) {
   return determineTransactionAttribute(method);
}
protected TransactionAttribute determineTransactionAttribute(AnnotatedElement ae) {
   for (TransactionAnnotationParser annotationParser : this.annotationParsers) {
      TransactionAttribute attr = annotationParser.parseTransactionAnnotation(ae);
      if (attr != null) {
         return attr;
      }
   }
   return null;
}

public TransactionAttribute parseTransactionAnnotation(AnnotatedElement ae) {
   AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
         ae, Transactional.class, false, false);
   if (attributes != null) {
      return parseTransactionAnnotation(attributes);
   }
   else {
      return null;
   }
}

到这块,我们就看到了我们想看到的获取注解标记的代码。首先会判断当前类是否含有Transactional注解,这是事务属性的基础,当然如果有的化会继续调用parseTransactionAnnotation方法解析详细的属性

protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
   RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
   //解析propagation
   Propagation propagation = attributes.getEnum("propagation");
   rbta.setPropagationBehavior(propagation.value());
    //解析isolation
   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"));
   ArrayList<RollbackRuleAttribute> rollBackRules = new ArrayList<>();
   Class<?>[] rbf = attributes.getClassArray("rollbackFor");
   for (Class<?> rbRule : rbf) {
      RollbackRuleAttribute rule = new RollbackRuleAttribute(rbRule);
      rollBackRules.add(rule);
   }
   String[] rbfc = attributes.getStringArray("rollbackForClassName");
   for (String rbRule : rbfc) {
      RollbackRuleAttribute rule = new RollbackRuleAttribute(rbRule);
      rollBackRules.add(rule);
   }
   Class<?>[] nrbf = attributes.getClassArray("noRollbackFor");
   for (Class<?> rbRule : nrbf) {
      NoRollbackRuleAttribute rule = new NoRollbackRuleAttribute(rbRule);
      rollBackRules.add(rule);
   }
   String[] nrbfc = attributes.getStringArray("noRollbackForClassName");
   for (String rbRule : nrbfc) {
      NoRollbackRuleAttribute rule = new NoRollbackRuleAttribute(rbRule);
      rollBackRules.add(rule);
   }
   rbta.getRollbackRules().addAll(rollBackRules);
   return rbta;
}

上面方法实现了对对应类或者方法的事务属性解析,你会看到这个类中你所属性的属性。至此,事务功能的初始化工作便结束了

事务增强器

springaop在事务进行调用的时候会走transactionInterceptor进行拦截

执行目标方法,进入invoke()

Spring声明事务源码分析

1.@EnableTransactionManagement开启到我们的事务

2.@Import(TransactionManagementConfigurationSelector.class)

3. AdviceMode mode() default AdviceMode.PROXY;默认使用 PROXY选择器

4.return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};

5.加上@EnableTransactionManagement这个注解将 :TransactionInterceptor,和InternalAutoProxyCreator这两个类注入到IOC容器中

6.进入AbstractAutoProxyCreater的后置处理器的wrapIfNecessary方法针对指定bean进行封装

####6.1.找出指定bean对应的增强器

####6.2.根据找出的增强器创建代理

7.执行目标方法

8.一旦出现异常,尝试异常处理,默认 对(RuntimeException回滚)

9.提交事务前的事务信息清除

10.提交事务。

本文参考

参考书籍:Spring源码深度解析

蚂蚁课堂:http://www.mayikt.com/

© 著作权归作者所有

须臾之余
粉丝 125
博文 67
码字总数 178724
作品 0
吉安
程序员
私信 提问
Spring5对比Spring3.2源码之容器的基本实现

最近看了《Spring源码深度解析》,该书是基于Spring3.2版本的,其中关于第二章容器的基本实现部分,目前spring5的实现方式已有较大改变。 Spring3.2的实现: 容器的基础XmlBeanFactory已经被...

Ilike_Java
2018/10/17
145
0
最新天猫3轮面试题目:虚拟机+并发锁+Sql防注入+Zookeeper

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/t4i2b10X4c22nF6A/article/details/83689192 一面 自我介绍、项目介绍 Spring拦截器、实现了哪些方法?底层原...

JAVA高级架构v
2018/11/03
0
0
TCC-Transaction 源码分析 —— TCC 实现

摘要: 原创出处 http://www.iocoder.cn/TCC-Transaction/tcc-core 「芋道源码」欢迎转载,保留摘要,谢谢! 本文主要基于 TCC-Transaction 1.2.3.3 正式版 1. 概述 2. TCC 原理 3. TCC-Trans...

Java公众号_芋道源码_每日更新
2018/10/28
0
0
Spring事务之切点解析详解

在Spring事务用法示例与实现原理中我们讲到,在进行标签解析的时候,Spring注册了三个bean:BeanFactoryTransactionAttributeSourceAdvisor,TransactionInterceptor和AnnotationTransaction...

爱宝贝丶
2018/09/05
853
0
spring源码--容器的基本实现

spring源码各版本下载地址: https://github.com/spring-projects/spring-framework/tags 在工作中见得非常多的容器使用是:

叫我北北
2018/06/29
0
0

没有更多内容

加载失败,请刷新页面

加载更多

java通过ServerSocket与Socket实现通信

首先说一下ServerSocket与Socket. 1.ServerSocket ServerSocket是用来监听客户端Socket连接的类,如果没有连接会一直处于等待状态. ServetSocket有三个构造方法: (1) ServerSocket(int port);...

Blueeeeeee
今天
6
0
用 Sphinx 搭建博客时,如何自定义插件?

之前有不少同学看过我的个人博客(http://python-online.cn),也根据我写的教程完成了自己个人站点的搭建。 点此:使用 Python 30分钟 教你快速搭建一个博客 为防有的同学不清楚 Sphinx ,这...

王炳明
昨天
5
0
黑客之道-40本书籍助你快速入门黑客技术免费下载

场景 黑客是一个中文词语,皆源自英文hacker,随着灰鸽子的出现,灰鸽子成为了很多假借黑客名义控制他人电脑的黑客技术,于是出现了“骇客”与"黑客"分家。2012年电影频道节目中心出品的电影...

badaoliumang
昨天
14
0
很遗憾,没有一篇文章能讲清楚线程的生命周期!

(手机横屏看源码更方便) 注:java源码分析部分如无特殊说明均基于 java8 版本。 简介 大家都知道线程是有生命周期,但是彤哥可以认真负责地告诉你网上几乎没有一篇文章讲得是完全正确的。 ...

彤哥读源码
昨天
15
0
jquery--DOM操作基础

本文转载于:专业的前端网站➭jquery--DOM操作基础 元素的访问 元素属性操作 获取:attr(name);$("#my").attr("src"); 设置:attr(name,value);$("#myImg").attr("src","images/1.jpg"); ......

前端老手
昨天
7
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部