Spring Boot源码-Transactional注解实现事务AOP原理


1 概述
2 Spring Boot配置入口
3 BeanFactoryTransactionAttributeSourceAdvisor事务AOP实现

1 概述

首先要先了解,Spring在通过@Transactional注解创建事务也是通过AOP实现的,具体的AOP创建入口,可以阅读笔者文章Spring Boot源码-Spring AOP创建代理的入口(但是在该文章只介绍了AOP的入口,没有介绍其具体实现)。通过该文章我们可以知道,Spring是通过BeanPostProcessor.postProcessAfterInitialization创建动态代理实现切面的。AnnotationAwareAspectJAutoProxyCreator是检测是否需要创建AOP织入的关键类。在实例化一个Bean时,其通过在容器中查找是否有能够使用在该bean相关方法上的Advisor来实现织入。

好了,理解了上面AOP的大概创建过程,后面再看注解@Transactional的实现就比较简单了。

2 Spring Boot配置入口

Spring Boot自动配置如何实现的就不再具体介绍了,首先我们可以在spring.factories文件中看到事务自动配置相关类TransactionAutoConfiguration,但是我们看其源码可以知道其类上有一个注解@ConditionalOnClass(PlatformTransactionManager.class),也就是说TransactionAutoConfiguration依赖PlatformTransactionManager,所以在启用事务时必须引入数据库相关的jar包。

下面我们看TransactionAutoConfiguration的嵌套内部类EnableTransactionManagementConfiguration,Spring在处理@Configuration注解的配置类时也会同步处理其所有内部类,通过源码可知EnableTransactionManagementConfiguration的生效要求存在PlatformTransactionManager.class类型的bean,PlatformTransactionManager.class类型的bean是在何时加入到容器中的呢?我们可以通过在TransactionAutoConfiguration源码上找到答案,TransactionAutoConfiguration类定义处有如下注解:

@AutoConfigureAfter({ JtaAutoConfiguration.class, HibernateJpaAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class, Neo4jDataAutoConfiguration.class })

我们这里看下DataSourceTransactionManagerAutoConfiguration.class,通过搜索可以知道DataSourceTransactionManagerAutoConfiguration也在spring.factories文件中,所以也会被注册到容器中,DataSourceTransactionManagerAutoConfiguration源码比较简单,就是向容器中注册了DataSourceTransactionManagerDataSourceTransactionManagerAutoConfiguration依赖的DateSource是通过spring.factories文件中的DataSourceAutoConfiguration注册到容器中的。

现在我们再回来看TransactionAutoConfiguration的嵌套内部类EnableTransactionManagementConfigurationEnableTransactionManagementConfiguration的两个内部类JdkDynamicAutoProxyConfigurationCglibAutoProxyConfiguration都使用类注解EnableTransactionManagement,而注解EnableTransactionManagement则使用了@Import(TransactionManagementConfigurationSelector.class)@Import注解的原理这里不具体介绍,这也是Spring Boot自动配置的关键。TransactionManagementConfigurationSelector则通过selectImports方法引入了配置AutoProxyRegistrarProxyTransactionManagementConfigurationAutoProxyRegistrar主要是保证如果容器中没有相关AOP增强类存在时,引入一个AOP增强类,为后面使用AOP实现事务作准备。ProxyTransactionManagementConfiguration就像容器注册了事务的关键实现类BeanFactoryTransactionAttributeSourceAdvisorTransactionAttributeSource以及TransactionInterceptor

3 BeanFactoryTransactionAttributeSourceAdvisor事务AOP实现

BeanFactoryTransactionAttributeSourceAdvisor就是查看方法是否存在@Transactional注解并决定是否创建事务的实现所在。BeanFactoryTransactionAttributeSourceAdvisor.pointcut实现如下:

//BeanFactoryTransactionAttributeSourceAdvisor
private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
    @Override
    @Nullable
    protected TransactionAttributeSource getTransactionAttributeSource() {
        //这里使用的是匿名内部类,所以返回的
        //transactionAttributeSource是
        //BeanFactoryTransactionAttributeSourceAdvisor
        //的域AnnotationTransactionAttributeSource
        return transactionAttributeSource;
    }
};

好了,在决定相关bean要不要采用事务控制时,我们看下上面源码中匿名类的父类TransactionAttributeSourcePointcut.matches方法实现:

//TransactionAttributeSourcePointcut
@Override
public boolean matches(Method method, Class targetClass) {
    //首先过滤一些框架内部使用的类
    if (TransactionalProxy.class.isAssignableFrom(targetClass) ||
            PlatformTransactionManager.class.isAssignableFrom(targetClass) ||
            PersistenceExceptionTranslator.class.isAssignableFrom(targetClass)) {
        return false;
    }
    //这个上面介绍过,返回的是
    //BeanFactoryTransactionAttributeSourceAdvisor
    //的域AnnotationTransactionAttributeSource
    TransactionAttributeSource tas = getTransactionAttributeSource();
    //因为tas为AnnotationTransactionAttributeSource,所以这里
    //通过tas.getTransactionAttribute查看该方法是否有事务相关注解
    //如果有的话,就需要通过AOP进行事务处理
    return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
}

下面我们看AnnotationTransactionAttributeSourcegetTransactionAttribute实现,该方法在AnnotationTransactionAttributeSource父类AbstractFallbackTransactionAttributeSource实现如下:

public TransactionAttribute getTransactionAttribute(Method method, @Nullable Class targetClass) {
    if (method.getDeclaringClass() == Object.class) {
        return null;
    }
    //首先查看缓存是否存在,避免重复解析事务元数据
    // First, see if we have a cached value.
    Object cacheKey = getCacheKey(method, targetClass);
    TransactionAttribute cached = this.attributeCache.get(cacheKey);
    if (cached != null) {
        // Value will either be canonical value indicating there is no transaction attribute,
        // or an actual transaction attribute.
        if (cached == NULL_TRANSACTION_ATTRIBUTE) {
            return null;
        }
        else {
            return cached;
        }
    }
    else {
        // We need to work it out.
        //尝试从方法中获取事务相关配置元数据
        TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
        //解析完之后放到缓存里
        // Put it in the cache.
        if (txAttr == null) {
            this.attributeCache.put(cacheKey, NULL_TRANSACTION_ATTRIBUTE);
        }
        else {
            String methodIdentification = ClassUtils.getQualifiedMethodName(method, targetClass);
            if (txAttr instanceof DefaultTransactionAttribute) {
                ((DefaultTransactionAttribute) txAttr).setDescriptor(methodIdentification);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
            }
            this.attributeCache.put(cacheKey, txAttr);
        }
        return txAttr;
    }
}

//根据不同的TransactionAttributeSource实现从不同的配置
//中读取元数据,这里因为采用注解,所有从注解中读取事务配置
//子类则通过重写findTransactionAttribute(Class clazz)
//以及findTransactionAttribute(Method method)方法提供从不同的
//配置方式中读取事务
protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class targetClass) {
    // Don't allow no-public methods as required.
    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    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;
}

下面我们看AnnotationTransactionAttributeSource.findTransactionAttribute(Class clazz)以及AnnotationTransactionAttributeSource.findTransactionAttribute(Method method)方法实现,其实这两个方法都调用了determineTransactionAttribute(AnnotatedElement element)方法:

//AnnotationTransactionAttributeSource
@Override
@Nullable
protected TransactionAttribute findTransactionAttribute(Class clazz) {
    return determineTransactionAttribute(clazz);
}

@Override
@Nullable
protected TransactionAttribute findTransactionAttribute(Method method) {
    return determineTransactionAttribute(method);
}

//determineTransactionAttribute则通过注册的一系列
//TransactionAnnotationParser从类或者方法注解中解析
//事务配置
@Nullable
protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) {
    for (TransactionAnnotationParser annotationParser : this.annotationParsers) {
        TransactionAttribute attr = annotationParser.parseTransactionAnnotation(element);
        if (attr != null) {
            return attr;
        }
    }
    return null;
}

//在AnnotationTransactionAttributeSource构造函数中,
//根据检测环境中的是否存在相关jpa实现的类,注册了相关的
//TransactionAnnotationParser
public AnnotationTransactionAttributeSource(boolean publicMethodsOnly) {
    this.publicMethodsOnly = publicMethodsOnly;
    if (jta12Present || ejb3Present) {
        this.annotationParsers = new LinkedHashSet<>(4);
        this.annotationParsers.add(new SpringTransactionAnnotationParser());
        if (jta12Present) {
            this.annotationParsers.add(new JtaTransactionAnnotationParser());
        }
        if (ejb3Present) {
            this.annotationParsers.add(new Ejb3TransactionAnnotationParser());
        }
    }
    else {
        this.annotationParsers = Collections.singleton(new SpringTransactionAnnotationParser());
    }
}

下面我们看默认的SpringTransactionAnnotationParser是如何完成事务配置解析的:

//SpringTransactionAnnotationParser
//到这里终于看到了熟悉的Transactional注解,下面过程就不再介绍了,
//主要就是读取Transactional注解中的关于事务的配置
public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
    AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(
            element, Transactional.class, false, false);
    if (attributes != null) {
        return parseTransactionAnnotation(attributes);
    }
    else {
        return null;
    }
}

你可能感兴趣的:(Spring Boot源码-Transactional注解实现事务AOP原理)