Spring注解开发(十四)——事务基本原理分析

目录

声明式事务实现原理

Demo

源码分析

1.@EnableTransactionManagement

2.AutoProxyRegistrar

3.ProxyTransactionManagementConfiguration:

3.1AnnotationTransactionAttributeSource:

3.2TransactionInterceptor:


基本步骤

  1. 配置数据源:DataSource
  2. 配置事务管理器来控制事务:PlatformTransactionManager
  3. @EnableTransactionManagement开启基于注解的事务管理功能
  4. 给方法上面标注@Transactional标识当前方法是一个事务方法

声明式事务实现原理

  1. @EnableTransactionManagement利用TransactionManagementConfigurationSelector给spring容器中导入两个组件:AutoProxyRegistrar和ProxyTransactionManagementConfiguration
  2. AutoProxyRegistrar给spring容器中注册一个InfrastructureAdvisorAutoProxyCreator,InfrastructureAdvisorAutoProxyCreator实现了InstantiationAwareBeanPostProcessor,InstantiationAwareBeanPostProcessor是一个BeanPostProcessor。它可以拦截spring的Bean初始化(Initialization)前后和实例化(Instantiation)前后。利用后置处理器机制在被拦截的bean创建以后包装该bean并返回一个代理对象代理对象执行方法利用拦截器链进行调用(同springAop的原理)
  3. ProxyTransactionManagementConfiguration:是一个spring的配置类,它为spring容器注册了一个BeanFactoryTransactionAttributeSourceAdvisor,是一个事务事务增强器。它有两个重要的字段:AnnotationTransactionAttributeSource和TransactionInterceptor。

    1. AnnotationTransactionAttributeSource:用于解析事务注解的相关信息
    2. TransactionInterceptor:事务拦截器,在事务方法执行时,都会调用TransactionInterceptor的invoke->invokeWithinTransaction方法,这里面通过配置的PlatformTransactionManager控制着事务的提交和回滚。

后面详细分析

Demo

pom依赖:

 <dependencies>
        <!--https://mvnrepository.com/artifact/org.springframework/spring-context-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
        </dependency>
        <!-- 数据池 -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>

配置类:

package com.cjian.tx;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@Configuration
@ComponentScan("com.cjian.tx")
@EnableTransactionManagement
public class TxConfig {
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        return dataSource;
    }
    @Bean
    public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
        return new JdbcTemplate(dataSource());
    }

    @Bean
    public PlatformTransactionManager platformTransactionManager() throws PropertyVetoException {
        return new DataSourceTransactionManager(dataSource());
    }
}

 如果不配置PlatformTransactionManager,会报异常

 

业务类:

package com.cjian.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.UUID;
@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insertUser(){
        String sql = "insert into user(name,age) values(?,?)";
        String name = UUID.randomUUID().toString().substring(0,5);
        jdbcTemplate.update(sql,name,22);
    }
}
package com.cjian.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    @Transactional
    public void inertUser(){
        userDao.insertUser();
        System.out.println("插入成功!");
        int i = 1/0;
    }
}
package com.cjian.test;

import com.cjian.tx.TxConfig;
import com.cjian.tx.UserService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestTx {

    static AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            TxConfig.class);

    public static void main(String[] args) {
        UserService userService = applicationContext.getBean(UserService.class);
        userService.inertUser();
        applicationContext.close();
    }
}

经测试,成功进行了事务的回滚,接下来我们来分析下原理:

源码分析

1.@EnableTransactionManagement

利用TransactionManagementConfigurationSelector给spring容器中导入两个组件:AutoProxyRegistrar和ProxyTransactionManagementConfiguration

@Import({TransactionManagementConfigurationSelector.class})
public @interface EnableTransactionManagement {
    boolean proxyTargetClass() default false;

    //注意这里有个属性 默认为AdviceMode.PROXY
    AdviceMode mode() default AdviceMode.PROXY;

    int order() default 2147483647;
}
public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
    public TransactionManagementConfigurationSelector() {
    }

    protected String[] selectImports(AdviceMode adviceMode) {
        switch(adviceMode) {
        case PROXY://事务类型走这里
            return new String[]{AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};
        case ASPECTJ:
            return new String[]{"org.springframework.transaction.aspectj.AspectJTransactionManagementConfiguration"};
        default:
            return null;
        }
    }
}

2.AutoProxyRegistrar

给spring容器中注册一个InfrastructureAdvisorAutoProxyCreator,InfrastructureAdvisorAutoProxyCreator实现了InstantiationAwareBeanPostProcessor,InstantiationAwareBeanPostProcessor是一个BeanPostProcessor。它可以拦截spring的Bean初始化(Initialization)前后和实例化(Initialization)前后。利用后置处理器机制在被拦截的bean创建以后包装该bean并返回一个代理对象代理对象执行方法利用拦截器链进行调用(同springAop的原理)

之前分析AOP的原理时,注册了一个这个:

 

所以分析到这里,大体也就清楚了,几乎同aop的原理一样:拦截目标方法(代理)的调用,如果捕获异常,则执行回滚,后面贴相关代码

InfrastructureAdvisorAutoProxyCreator相当于一个后置处理器:

3.ProxyTransactionManagementConfiguration

是一个spring的配置类,它为spring容器注册了一个BeanFactoryTransactionAttributeSourceAdvisor,是一个事务事务增强器。它有两个重要的字段:AnnotationTransactionAttributeSource和TransactionInterceptor。

3.1AnnotationTransactionAttributeSource:

用于解析事务注解的相关信息

     一一对应   

解析完成之后放在了TransactionInterceptor里面(保存了事务属性信息以及事务管理器)

3.2TransactionInterceptor:

事务拦截器,在事务方法执行时,都会调用TransactionInterceptor的invoke->invokeWithinTransaction方法,这里面通过配置的PlatformTransactionManager控制着事务的提交和回滚。

同aop的方法拦截器

final TransactionAttribute txAttr = this.getTransactionAttributeSource().getTransactionAttribute(method, targetClass);--->获取事务的相关属性
final PlatformTransactionManager tm = this.determineTransactionManager(txAttr);--->获取PlatformTransactionManager

打个断点,捕获到异常,确实是走到了这里,进行回滚

 

如果业务正常:

提交事务

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值