zoukankan      html  css  js  c++  java
  • spring注解-事务

    一、环境搭建

    • 导入Spring-jdbc模块
    • @EnableTransactionManagement 开启基于注解的事务管理功能
    等同于xml配置<tx:annotation-driven/>
    • 配置事务管理器来控制事务
        @Bean
        public PlatformTransactionManager transactionManager() throws Exception{
            return new DataSourceTransactionManager(dataSource());
        }
    • 在需要事务的方法上标注 @Transactional

    二、原理

    @EnableTransactionManagement

      利用TransactionManagementConfigurationSelector给容器中导入AutoProxyRegistrar、ProxyTransactionManagementConfiguration

    AutoProxyRegistrar

      给容器中注册一个InfrastructureAdvisorAutoProxyCreator组件(利用后置处理器机制在对象创建以后包装对象,返回一个代理对象,代理对象执行方法利用拦截器链进行调用)

    ProxyTransactionManagementConfiguration

      事务的配置文件,它给容器中注册事务增强器的bean,而在事务增强器里面需要两个属性

    1. AnnotationTransactionAttributeSource:解析事务注解的信息
    2. TransactionInterceptor:事务拦截器;它保存了事务属性信息、事务管理器(并且它实现了MethodInterceptor,在目标方法执行的时候进行拦截,执行拦截器链)
      • 先获取事务相关的属性,再获取PlatformTransactionManager,如果事先没有添加指定任何transactionmanger,最终会从容器中按照类型获取一个PlatformTransactionManager
      • 执行目标方法;如果异常,获取到事务管理器,利用事务管理回滚操作;如果正常,利用事务管理器,提交事务
  • 相关阅读:
    spring-boot 速成(6) 整合disconf
    spring-boot 速成(5) profile区分环境
    dubbox REST服务使用fastjson替换jackson
    resteasy经验谈
    spring-boot 速成(4) 自定义配置
    spring-boot 速成(3) actuator
    idea 高级调试技巧
    spring-boot 速成(2) devtools之热部署及LiveReload
    bash编程之xargs实用技巧
    spring-boot 速成(1) helloworld
  • 原文地址:https://www.cnblogs.com/edda/p/13488215.html
Copyright © 2011-2022 走看看