@Transactional Springboot source code analysis of the

Summary:

On SpringBoothow to understand, in fact, it is to see you on Spring Frameworkhow familiar - such as SpringBoota large number of module assembly design model, in fact it belongs to the ability to Spring Framework provides. SpringBoot popular today, based on the XMLuse of Spring Framework configuration doomed thing of the past. Annotation-driven applications-oriented programming metadata is already subject to a preference for more and more developers, after all, it's convenient degree, the advantages of XML is unparalleled way.

    @Configuration
    @ConditionalOnClass({PlatformTransactionManager.class})
    @AutoConfigureAfter({JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, Neo4jDataAutoConfiguration.class})
    @EnableConfigurationProperties({TransactionProperties.class})
    public class TransactionAutoConfiguration {
        public TransactionAutoConfiguration() {
        }
    
        @Bean
        @ConditionalOnMissingBean
        public TransactionManagerCustomizers platformTransactionManagerCustomizers(ObjectProvider<PlatformTransactionManagerCustomizer<?>> customizers) {
            return new TransactionManagerCustomizers((Collection)customizers.orderedStream().collect(Collectors.toList()));
        }
    
        @Configuration
        @ConditionalOnBean({PlatformTransactionManager.class})
        @ConditionalOnMissingBean({AbstractTransactionManagementConfiguration.class})
        public static class EnableTransactionManagementConfiguration {
            public EnableTransactionManagementConfiguration() {
            }
    
            @Configuration
            @EnableTransactionManagement(
                proxyTargetClass = true
            )
            @ConditionalOnProperty(
                prefix = "spring.aop",
                name = {"proxy-target-class"},
                havingValue = "true",
                matchIfMissing = true
            )
          //默认采用cglib代理
            public static class CglibAutoProxyConfiguration {
                public CglibAutoProxyConfiguration() {
                }
            }
    
            @Configuration
            @EnableTransactionManagement(
                proxyTargetClass = false
            )
            @ConditionalOnProperty(
                prefix = "spring.aop",
                name = {"proxy-target-class"},
                havingValue = "false",
                matchIfMissing = false
            )
            public static class JdkDynamicAutoProxyConfiguration {
                public JdkDynamicAutoProxyConfiguration() {
                }
            }
        }
    
        @Configuration
      //当PlatformTransactionManager类型的bean存在并且当存在多个bean时指定为Primary的 PlatformTransactionManager存在时,该配置类才进行解析
        @ConditionalOnSingleCandidate(PlatformTransactionManager.class)
        public static class TransactionTemplateConfiguration {
            private final PlatformTransactionManager transactionManager;
    
            public TransactionTemplateConfiguration(PlatformTransactionManager transactionManager) {
                this.transactionManager = transactionManager;
            }
    
         // 由于TransactionAutoConfiguration是在DataSourceTransactionManagerAutoConfiguration之后才被解析处理的,而在DataSourceTransactionManagerAutoConfiguration中配置了transactionManager,因此, TransactionTemplateConfiguration 会被处理.
            @Bean
            @ConditionalOnMissingBean
            public TransactionTemplate transactionTemplate() {
                return new TransactionTemplate(this.transactionManager);
            }
        }
    }
PlatformTransactionManager subsequent chapters analyze

Tip: Use @EnableTransactionManagementpre-annotation. Be sure that you have configured at least one PlatformTransactionManagerof Bean, otherwise it will error. (Of course, you can also achieve TransactionManagementConfigurerto provide an exclusive, but we generally do not do so ~ ~ ~)

Open comments driver

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Import({TransactionManagementConfigurationSelector.class})
    public @interface EnableTransactionManagement {
        boolean proxyTargetClass() default false;
        AdviceMode mode() default AdviceMode.PROXY;
        int order() default 2147483647;
    }

Simply and @EnableAsyncannotated exactly the same. Except that only the @Importintroducer introduced into this class.

Compare

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Import(AsyncConfigurationSelector.class)
    public @interface EnableAsync {
        // 支持自定义注解类型 去支持异步~~~
        Class<? extends Annotation> annotation() default Annotation.class;
        boolean proxyTargetClass() default false;
        AdviceMode mode() default AdviceMode.PROXY;
        int order() default Ordered.LOWEST_PRECEDENCE;
    }

TransactionManagementConfigurationSelector

    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[]{this.determineTransactionAspectClass()};
            default:
                return null;
            }
        }
    
        private String determineTransactionAspectClass() {
            return ClassUtils.isPresent("javax.transaction.Transactional", this.getClass().getClassLoader()) ? "org.springframework.transaction.aspectj.AspectJJtaTransactionManagementConfiguration" : "org.springframework.transaction.aspectj.AspectJTransactionManagementConfiguration";
        }
    }

Still can see and @EnableAsyncimport the AsyncConfigurationSelectorsame, inherits from AdviceModeImportSelector, after all, the same pattern, by analogy, a pass Belden ~

AdviceModeImportSelectorCurrently three sub-categories are AsyncConfigurationSelectorknown: TransactionManagementConfigurationSelector, CachingConfigurationSelector, . This shows that also focuses on the back Springcaching system @EnableCaching, and this model is very similar ~~~

AutoProxyRegistrar

It is ImportBeanDefinitionRegistrar, you can achieve your own definition information to register Bean container

    // @since 3.1
    public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
        private final Log logger = LogFactory.getLog(this.getClass());
    
        public AutoProxyRegistrar() {
        }
    
        public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
            boolean candidateFound = false;
            // 这里面需要特别注意的是:这里是拿到所有的注解类型~~~而不是只拿@EnableAspectJAutoProxy这个类型的
            // 原因:因为mode、proxyTargetClass等属性会直接影响到代理得方式,而拥有这些属性的注解至少有:
            // @EnableTransactionManagement、@EnableAsync、@EnableCaching等~~~~
            // 甚至还有启用AOP的注解:@EnableAspectJAutoProxy它也能设置`proxyTargetClass`这个属性的值,因此也会产生关联影响~
            Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
            Iterator var5 = annTypes.iterator();
    
            while(var5.hasNext()) {
                String annType = (String)var5.next();
                AnnotationAttributes candidate = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
                if (candidate != null) {
                    Object mode = candidate.get("mode");
                    Object proxyTargetClass = candidate.get("proxyTargetClass");
                  // 如果存在mode且存在proxyTargetClass 属性
                // 并且两个属性的class类型也是对的,才会进来此处(因此其余注解相当于都挡外面了~)
                    if (mode != null && proxyTargetClass != null && AdviceMode.class == mode.getClass() && Boolean.class == proxyTargetClass.getClass()) {
                        candidateFound = true;
                        if (mode == AdviceMode.PROXY) {
                          
                        // 它主要是注册了一个`internalAutoProxyCreator`,但是若出现多次的话,这里不是覆盖的形式,而是以优先级的形式
                            AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
                          //看要不要强制使用CGLIB的方式(由此可以发现  这个属性若出现多次,是会是覆盖的形式)
                            if ((Boolean)proxyTargetClass) {
                                AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
                                return;
                            }
                        }
                    }
                }
            }
    
            if (!candidateFound && this.logger.isInfoEnabled()) {
                String name = this.getClass().getSimpleName();
                this.logger.info(String.format("%s was imported but no annotations were found having both 'mode' and 'proxyTargetClass' attributes of type AdviceMode and boolean respectively. This means that auto proxy creator registration and configuration may not have occurred as intended, and components may not be proxied as expected. Check to ensure that %s has been @Import'ed on the same class where these annotations are declared; otherwise remove the import of %s altogether.", name, name, name));
            }
        }
    }

Tracking AopConfigUtilsthe source code you will find that this transaction is injected into a vessel InfrastructureAdvisorAutoProxyCreator, and see if it is adopted CGLIBor JDKagent. It is mainly read the Advisorclass, and in line with the secondary proxy bean.

Proxy Transaction Management Configuration

    @Configuration
    public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
        public ProxyTransactionManagementConfiguration() {
        }
    
        @Bean(
            name = {"org.springframework.transaction.config.internalTransactionAdvisor"}
        )
        @Role(2)
        public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
            BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
            advisor.setTransactionAttributeSource(this.transactionAttributeSource());
            advisor.setAdvice(this.transactionInterceptor());
            if (this.enableTx != null) {
              // 顺序由@EnableTransactionManagement注解的Order属性来指定 默认值为:Ordered.LOWEST_PRECEDENCE
                advisor.setOrder((Integer)this.enableTx.getNumber("order"));
            }
    
            return advisor;
        }
    
        @Bean
        @Role(2)
        // TransactionAttributeSource 这种类特别像 `TargetSource`这种类的设计模式
        public TransactionAttributeSource transactionAttributeSource() {
            return new AnnotationTransactionAttributeSource();
        }
    
        @Bean
        @Role(2)
      // 事务拦截器,它是个`MethodInterceptor`,它也是Spring处理事务最为核心的部分
        // 请注意:你可以自己定义一个TransactionInterceptor(同名的),来覆盖此Bean
        public TransactionInterceptor transactionInterceptor() {
            TransactionInterceptor interceptor = new TransactionInterceptor();
            interceptor.setTransactionAttributeSource(this.transactionAttributeSource());
            if (this.txManager != null) {
                interceptor.setTransactionManager(this.txManager);
            }
            return interceptor;
        }
    }
    @Configuration
    public abstract class AbstractTransactionManagementConfiguration implements ImportAware {
        @Nullable
        protected AnnotationAttributes enableTx;
       
      // 此处:注解的默认的事务处理器(可议通过实现接口TransactionManagementConfigurer来自定义配置)
        // 因为事务管理器这个东西,一般来说全局一个就行,但是Spring也提供了定制化的能力~~~
          @Nullable
        protected PlatformTransactionManager txManager;
    
        public AbstractTransactionManagementConfiguration() {
        }
    
        public void setImportMetadata(AnnotationMetadata importMetadata) {
            this.enableTx = AnnotationAttributes.fromMap(importMetadata.getAnnotationAttributes(EnableTransactionManagement.class.getName(), false));
          //这个注解@EnableTransactionManagement是必须的~~~~~~~~~~~~~~~~否则报错了
            if (this.enableTx == null) {
                throw new IllegalArgumentException("@EnableTransactionManagement is not present on importing class " + importMetadata.getClassName());
            }
        }
    
        @Autowired(
            required = false
        )
      // 这里和@Async的处理一样,配置文件可以实现这个接口。然后给注解驱动的给一个默认的事务管理器~~~~
        void setConfigurers(Collection<TransactionManagementConfigurer> configurers) {
            if (!CollectionUtils.isEmpty(configurers)) {
              // 同样的,最多也只允许你去配置一个~~~
                if (configurers.size() > 1) {
                    throw new IllegalStateException("Only one TransactionManagementConfigurer may exist");
                } else {
                    TransactionManagementConfigurer configurer = (TransactionManagementConfigurer)configurers.iterator().next();
                    this.txManager = configurer.annotationDrivenTransactionManager();
                }
            }
        }
    
        @Bean(
            name = {"org.springframework.transaction.config.internalTransactionalEventListenerFactory"}
        )
        @Role(2)
        public static TransactionalEventListenerFactory transactionalEventListenerFactory() {
            return new TransactionalEventListenerFactory();
        }
    }

BeanFactoryTransactionAttributeSourceAdvisor

file

TransactionAttributeSourcePointcut

This is the match of affairs Pointcutsection, determine which classes need to generate proxy objects in order to apply the transaction.

    // 首先它的访问权限事default 显示是给内部使用的
    // 首先它继承自StaticMethodMatcherPointcut   所以`ClassFilter classFilter = ClassFilter.TRUE;` 匹配所有的类
    // 并且isRuntime=false  表示只需要对方法进行静态匹配即可~~~~
    abstract class TransactionAttributeSourcePointcut extends StaticMethodMatcherPointcut implements Serializable {
    
        // 方法的匹配  静态匹配即可(因为事务无需要动态匹配这么细粒度~~~)
        @Override
        public boolean matches(Method method, Class<?> targetClass) {
            // 实现了如下三个接口的子类,就不需要被代理了  直接放行
            // TransactionalProxy它是SpringProxy的子类。  如果是被TransactionProxyFactoryBean生产出来的Bean,就会自动实现此接口,那么就不会被这里再次代理了
            // PlatformTransactionManager:spring抽象的事务管理器~~~
            // PersistenceExceptionTranslator对RuntimeException转换成DataAccessException的转换接口
            if (TransactionalProxy.class.isAssignableFrom(targetClass) ||
                    PlatformTransactionManager.class.isAssignableFrom(targetClass) ||
                    PersistenceExceptionTranslator.class.isAssignableFrom(targetClass)) {
                return false;
            }
            
            // 重要:拿到事务属性源~~~~~~
            // 如果tas == null表示没有配置事务属性源,那是全部匹配的  也就是说所有的方法都匹配~~~~(这个处理还是比较让我诧异的~~~)
            // 或者 标注了@Transaction这样的注解的方法才会给与匹配~~~
            TransactionAttributeSource tas = getTransactionAttributeSource();
            return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
        }   
        ...
        // 由子类提供给我,告诉事务属性源~~~
        @Nullable
        protected abstract TransactionAttributeSource getTransactionAttributeSource();
    }

@Transactional

This transaction annotation can be used in class, it can also be used in the method.

  • The transaction annotation to mark the service component class level, equivalent for each service method service components are applied to this comment
  • Application Notes affairs at the method level, is a more fine-grained way Affairs notes

Note: If you have a property on the transaction annotation method and the method of their class, priority use transaction annotation property on the method.

In addition, Spring supports three different transactions Note:

  • Spring transaction commentorg.springframework.transaction.annotation.Transactional
  • JTA transaction annotation · javax.transaction.Transactional ·
  • EJB 3 transaction annotation · javax.ejb.TransactionAttribute ·

Custom TransactionManagementConfigurer

    @Configuration
    @EnableTransactionManagement
    public class MyTransactionManagementConfigurer implements TransactionManagementConfigurer {
        @Bean
        public PlatformTransactionManager transactionManager(DataSource dataSource) {
            DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
            return dataSourceTransactionManager;
        }
    
        @Override
        public PlatformTransactionManager annotationDrivenTransactionManager() {
            return null;
        }
    }

@EnableAspectJAutoProxy and @EnableTransactionManagement priority?

  • @EnableAspectJAutoProxyI would like vessel injectionAnnotationAwareAspectJAutoProxyCreator
  • @EnableTransactionManagementI would like vessel injectionInfrastructureAdvisorAutoProxyCreator
    public abstract class AopConfigUtils {
        ...
        @Nullable
        private static BeanDefinition registerOrEscalateApcAsRequired(
                Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {
            
            // 可以发现这里有一个很巧妙的处理:会对自动代理创建器进行升级~~~~
            // 所以如果你第一次进来的是`InfrastructureAdvisorAutoProxyCreator`,第二次进来的是`AnnotationAwareAspectJAutoProxyCreator`,那就会取第二次进来的这个Class
            // 反之则不行。这里面是维护的一个优先级顺序的,具体参看本类的static代码块,就是顺序  最后一个`AnnotationAwareAspectJAutoProxyCreator`才是最为强大的
            if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
                BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
                if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
                    int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
                    int requiredPriority = findPriorityForClass(cls);
                    if (currentPriority < requiredPriority) {
                        apcDefinition.setBeanClassName(cls.getName());
                    }
                }
                return null;
            }
    
            RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
            beanDefinition.setSource(source);
            beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
            beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
            registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
            return beanDefinition;
        }
        ...
    }

From the above analysis we can know: Whether you how many of these notes, regardless of their order, it has an internal mechanism of the priority boost slightly downward to ensure coverage compatible. Therefore, under normal circumstances, we are using the most advanced of AnnotationAwareAspectJAutoProxyCreatorthe auto proxy creator ~ ~ ~

Guess you like

Origin www.cnblogs.com/qinzj/p/11420840.html