【1】spring创建bean调用链

1)创建AnnotationConfigApplicationContext

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

2)调用其refresh()方法

3)调用 finishBeanFactoryInitialization方法

4)调用 beanFactory.preInstantiateSingletons();

5)接着调用 DefaultListableBeanFactory-getBean()

public Object getBean(String name) throws BeansException {
    return this.doGetBean(name, (Class)null, (Object[])null, false);
}

6)调用 doGetBean方法

7)调用 createBean方法

8)调用AbstractAutowireCapableBeanFactory-createBean方法

9)调用doCreateBean方法

10)调用initializeBean 方法

11)调用  applyBeanPostProcessorsAfterInitialization 方法

12)遍历所有 BeanPostProcessor-bean后置处理器,调用其postProcessAfterInitialization方法


【2】spring事务源码分析

1)spring通过@EnableTransactionManagement注解开启事务管理;

2)@EnableTransactionManagement通过TransactionManagementConfigurationSelector注册了2个bean;

  • AutoProxyRegistrar:自动代理注册器;它注册了一个 

    InfrastructureAdvisorAutoProxyCreator-BeanPostProcessor ;

    • 这个BeanPostProcessor 与上述【1】中的第12步对应上,对于@Transactional注解方法所属的类创建bean时,会执行 InfrastructureAdvisorAutoProxyCreator 这个后置处理器的postProcessAfterInitialization 方法

  • ProxyTransactionManagementConfiguration:代理事务管理配置;ProxyTransactionManagementConfiguration 引入了3个类:
    • BeanFactoryTransactionAttributeSourceAdvisor;(spring事务切面类

    • TransactionAttributeSource;

    • TransactionInterceptor ;


【2.1】InfrastructureAdvisorAutoProxyCreator-postProcessAfterInitialization(bean初始化后的后置处理方法)

@Nullable
    public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
        if (bean != null) {
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            if (this.earlyBeanReferences.remove(cacheKey) != bean) {
                return this.wrapIfNecessary(bean, beanName, cacheKey);
            }
        }

        return bean;
    }

1)它会调用AbstractAutoProxyCreator-wrapIfNecessary方法; 

2)调用AbstractAutoProxyCreator-createProxy方法创建代理; 

3)调用AbstractAutoProxyCreator-buildProxy方法

4)调用proxyFactory.getProxy(classLoader)

5)调用 this.createAopProxy().getProxy(classLoader)

6)调用 JdkDynamicAopProxy-getProxy方法-- JDK动态代理; 

public Object getProxy(@Nullable ClassLoader classLoader) {
        if (logger.isTraceEnabled()) {
            logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
        }

        return Proxy.newProxyInstance(this.determineClassLoader(classLoader), this.cache.proxiedInterfaces, this);
    }

7)显然this就是 InvocationHandler,所以JdkDynamicAopProxy的invoke方法就是spring事务的增强逻辑i;

8)JdkDynamicAopProxy-invoke()方法重点逻辑如下:

List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
                Object retVal;
                if (chain.isEmpty()) {
                    Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                    retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
                } else {
                    MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
                    retVal = invocation.proceed();
                }

9)调用ReflectiveMethodInvocation-proceed()方法

public Object proceed() throws Throwable {
        if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
            return this.invokeJoinpoint();
        } else {
            Object interceptorOrInterceptionAdvice = this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
            if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
                InterceptorAndDynamicMethodMatcher dm = (InterceptorAndDynamicMethodMatcher)interceptorOrInterceptionAdvice;
                Class<?> targetClass = this.targetClass != null ? this.targetClass : this.method.getDeclaringClass();
                return dm.matcher().matches(this.method, targetClass, this.arguments) ? dm.interceptor().invoke(this) : this.proceed();
            } else {
                return ((MethodInterceptor)interceptorOrInterceptionAdvice).invoke(this);
            }
        }
    }

10)调用 MethodInterceptor.invoke方法执行spring事务增强逻辑

即spring中JDK代理的通知,需要实现 MethodInterceptor接口,


【2.1.1】spring通过代理实现事务管理的invoke方法模拟

// JdkDynamicAopProxy类-invoke()方法-spring事务增强逻辑:
// @Transactional注解方法的增强逻辑的模拟 

 invoke() {
    MethodInterceptor mi = new MethodIntercepor();
    mi.invoke(); // 增强逻辑 
    target.proceed(); // 实际方法执行,如@Transactional注解方法的执行;
}

【2.1.2】InfrastructureAdvisorAutoProxyCreator-postProcessAfterInitialization()-bean后置处理器方法

当创建springbean时,若bean存在@Transactional修饰的方法,则创建bean的代理时,新增spring事务切面-BeanFactoryTransactionAttributeSourceAdvisor

1)InfrastructureAdvisorAutoProxyCreator继承AbstractAutoProxyCreator, 调用AbstractAutoProxyCreator-postProcessAfterInitialization方法

public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
        if (bean != null) {
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            if (this.earlyBeanReferences.remove(cacheKey) != bean) {
                return this.wrapIfNecessary(bean, beanName, cacheKey);
            }
        }

        return bean;
    }

2)调用wrapIfNecessary方法;

3)调用getAdvicesAndAdvisorsForBean获取事务切面bean,然后再调用createProxy()获取代理对象;【本章节主要分析getAdvicesAndAdvisorsForBean方法,createProxy在2.1章节分析过】

4)getAdvicesAndAdvisorsForBean 调用findEligibleAdvisors (找到符合条件的切面类)

5)调用 findAdvisorsThatCanApply

6)调用  AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass)

  • candidateAdvisors 是各个候选切面bean,就包括了章节1提到的 ProxyTransactionManagementConfiguration引入的BeanFactoryTransactionAttributeSourceAdvisor切面类的bean;

7)调用  canApply(candidate, clazz, hasIntroductions) ; cadidate是候选切面bean,如BeanFactoryTransactionAttributeSourceAdvisor

8)调用  canApply(pca.getPointcut(), targetClass, hasIntroductions)

pca.getPointcut() 调用的是 BeanFactoryTransactionAttributeSourceAdvisor.getPointcut()方法;实际返回的是  TransactionAttributeSourcePointcut bean ;即pointcut=TransactionAttributeSourcePointcut ; 

public class BeanFactoryTransactionAttributeSourceAdvisor extends AbstractBeanFactoryPointcutAdvisor {
    private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut();

    public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) {
        this.pointcut.setTransactionAttributeSource(transactionAttributeSource);
    }

    public void setClassFilter(ClassFilter classFilter) {
        this.pointcut.setClassFilter(classFilter);
    }

    public Pointcut getPointcut() {
        return this.pointcut;
    }
}

而 TransactionAttributeSourcePointcut的TransactionAttributeSource属性就是 

ProxyTransactionManagementConfiguration 创建的AnnotationTransactionAttributeSource-bean。 即 TransactionAttributeSource = AnnotationTransactionAttributeSource

public TransactionAttributeSource transactionAttributeSource() {
        return new AnnotationTransactionAttributeSource(false);
    }

9)调用 pc.getMethodMatcher(); 获取 MethodMatcher 方法匹配器;

pc,即pointcut切点(拦截规则) : TransactionAttributeSourcePointcut ;

而 TransactionAttributeSourcePointcut.getMethodMatcher() 返回的是this本身;

即 methodMatcher=TransactionAttributeSourcePointcut

10)调用 methodMatcher.matches(method, targetClass); 该方法返回匹配结果true/false

 public boolean matches(Method method, Class<?> targetClass) {
        return this.transactionAttributeSource == null || this.transactionAttributeSource.getTransactionAttribute(method, targetClass) != null;
    }

11)调用 transactionAttributeSource.getTransactionAttribute(method, targetClass)

transactionAttributeSource = AnnotationTransactionAttributeSource

12)调用 AnnotationTransactionAttributeSource父类 AbstractFallbackTransactionAttributeSource的getTransactionAttribute()

13)调用 ransactionAttribute txAttr = this.computeTransactionAttribute(method, targetClass) 获取事务属性;

AbstractFallbackTransactionAttributeSource-computeTransactionAttribute()

// 若 method不是public方法,则返回空属性;这就是为什么@Transactional方法不是public,则spring事务失效的原因

protected TransactionAttribute computeTransactionAttribute(Method method, @Nullable Class<?> targetClass) {
        // 若 method不是public方法,则返回空属性;
        if (this.allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
            return null;
        } else {
            Method specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
            TransactionAttribute txAttr = this.findTransactionAttribute(specificMethod);
            if (txAttr != null) {
                return txAttr;
            } else {
                txAttr = this.findTransactionAttribute(specificMethod.getDeclaringClass());
                if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
                    return txAttr;
                } else {
                    if (specificMethod != method) {
                        txAttr = this.findTransactionAttribute(method);
                        if (txAttr != null) {
                            return txAttr;
                        }

                        txAttr = this.findTransactionAttribute(method.getDeclaringClass());
                        if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
                            return txAttr;
                        }
                    }

                    return null;
                }
            }
        }
    }

14)调用 findTransactionAttribute方法

15)调用 AnnotationTransactionAttributeSource-findTransactionAttribute()方法

16)调用 determineTransactionAttribute() 方法

protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) {
        for(TransactionAnnotationParser parser : this.annotationParsers) {
            TransactionAttribute attr = parser.parseTransactionAnnotation(element);
            if (attr != null) {
                return attr;
            }
        }

        return null;
    }

获取注解解析器,通过注解解析器解析事务注解的属性,并封装到 TransactionAttribute类;

其中有一个解析器是 SpringTransactionAnnotationParser

17)调用SpringTransactionAnnotationParser-parseTransactionAnnotattion方法;

public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
        AnnotationAttributes attributes = AnnotatedElementUtils.findMergedAnnotationAttributes(element, Transactional.class, false, false);
        return attributes != null ? this.parseTransactionAnnotation(attributes) : null;
    }

    public TransactionAttribute parseTransactionAnnotation(Transactional ann) {
        return this.parseTransactionAnnotation(AnnotationUtils.getAnnotationAttributes(ann, false, false));
    }

// 解析事务注解的属性
    protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
        RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();
        Propagation propagation = (Propagation)attributes.getEnum("propagation");
        rbta.setPropagationBehavior(propagation.value());
        Isolation isolation = (Isolation)attributes.getEnum("isolation");
        rbta.setIsolationLevel(isolation.value());
        rbta.setTimeout(attributes.getNumber("timeout").intValue());
        String timeoutString = attributes.getString("timeoutString");
        Assert.isTrue(!StringUtils.hasText(timeoutString) || rbta.getTimeout() < 0, "Specify 'timeout' or 'timeoutString', not both");
        rbta.setTimeoutString(timeoutString);
        rbta.setReadOnly(attributes.getBoolean("readOnly"));
        rbta.setQualifier(attributes.getString("value"));
        rbta.setLabels(Set.of(attributes.getStringArray("label")));
        List<RollbackRuleAttribute> rollbackRules = new ArrayList();

        for(Class<?> rbRule : attributes.getClassArray("rollbackFor")) {
            rollbackRules.add(new RollbackRuleAttribute(rbRule));
        }

        for(String rbRule : attributes.getStringArray("rollbackForClassName")) {
            rollbackRules.add(new RollbackRuleAttribute(rbRule));
        }

        for(Class<?> rbRule : attributes.getClassArray("noRollbackFor")) {
            rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
        }

        for(String rbRule : attributes.getStringArray("noRollbackForClassName")) {
            rollbackRules.add(new NoRollbackRuleAttribute(rbRule));
        }

        rbta.setRollbackRules(rollbackRules);
        return rbta;
    }


【2.2】@EnableTransactionManagement引入第2个类:ProxyTransactionManagementConfiguration

1)ProxyTransactionManagementConfiguration创建了3个Bean:

  • BeanFactoryTransactionAttributeSourceAdvisor; spring事务切面类; 
  • TransactionAttributeSource;事务属性源;
  • TransactionInterceptor;通知,即spring事务方法执行的增强逻辑

【2.2.1】TransactionInterceptor-invoke方法

public Object invoke(MethodInvocation invocation) throws Throwable {
        Class<?> targetClass = invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null;
        Method var10001 = invocation.getMethod();
        Objects.requireNonNull(invocation);
        return this.invokeWithinTransaction(var10001, targetClass, invocation::proceed);
    }

1)调用 TransactionAspectSupport-invokeWithinTransaction方法


【2.3】调用@Transactional的底层执行流程

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐