AoP应用之事务(1) 事务类的引入

303 阅读2分钟

说明:本系列事务相关代码为spring boot starter jdbc内置,版本为2.1.1.RELEASE,spring tx的版本为5.1.3.RELEASE。

众所周知,AoP有一个重要的应用那就是事务,Spring中的事务分为编程式事务和声明式事务, 此篇中讲的是声明式事务。在正文开始之前,假设你已经了解了mysql基础知识,IoC中bean的实例化以及创建AoP代理类的过程。
SpringBoot中,事务的配置很简单,常见操作是在启动类声明@EnableTransactionManagement注解或者@EnableAutoConfiguration注解,然后在服务类声明@Transactional注解,最后用bean的实例调用含有注解的方法即可。接下来将会对这两个注解在事务方面的作用进行分析。

@EnableTransactionManagement

进入EnableTransactionManagement类,发现上方带有@Import(TransactionManagementConfigurationSelector.class),进入TransactionManagementConfigurationSelector类,发现其是ImportSelector接口的实现类,于是找到其selectImports方法

AdviceModeImportSelector->selectImports():
    // 找到TransactionManagementConfigurationSelector的泛型类,此处是EnableTransactionManagement
    Class<?> annType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);	
    // 注解没有更改任何的配置,所以都是默认值
    AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
    // 这里的adviceMode即为默认值PROXY
    AdviceMode adviceMode = attributes.getEnum(getAdviceModeAttributeName());
    String[] imports = selectImports(adviceMode);
    return imports;
TransactionManagementConfigurationSelector->selectImports():
    switch (adviceMode) {
        case PROXY:
            return new String[] {AutoProxyRegistrar.class.getName(),
                    ProxyTransactionManagementConfiguration.class.getName()};
    }

引入了AutoProxyRegistrar和ProxyTransactionManagementConfiguration这两个bean,看来它们将会是事务逻辑实现的起源了

@EnableAutoConfiguration

进入EnableAutoConfiguration类,发现上方带有@Import(AutoConfigurationImportSelector.class),进入AutoConfigurationImportSelector类,发现是DeferredImportSelector接口的实现类,一般手动写都是实现ImportSelector接口,而且在整个SpringBoot中,也只有这一个类实现的是DeferredImportSelector接口,所以直接讲结论

AutoConfigurationImportSelector->AutoConfigurationGroup->selectImports():
    Set<String> processedConfigurations = this.autoConfigurationEntries.stream()
        .map(AutoConfigurationEntry::getConfigurations)
        .flatMap(Collection::stream)
        .collect(Collectors.toCollection(LinkedHashSet::new));

processedConfigurations是将会使用到的配置类bean全限定名,截取其中一部分属性如下,其中org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration是与事务自动配置有关的。(关于配置类bean的由来请点击此处 进入TransactionAutoConfiguration类,见到如下属性,说明事务类的引入最终还是利用@EnableTransactionManagement这个注解。

其他

SpringBoot启动类中,使用@SpringBootApplication这个注解就能满足大多数情况,这是因为它内部的@SpringBootConfiguration可以让IoC容器找到启动类、@EnableAutoConfiguration只要maven引入依赖就能加载自动配置、@ComponentScan扫描项目工程中的bean,可见SpringBoot确实可以简化大部分的配置,以达到让开发者专注于业务逻辑代码的目的。