事务源码解析

本文深入探讨了事务的概念,包括ACID特性,并详细解析了Spring事务管理的三大核心接口:PlatformTransactionManager、TransactionDefinition和TransactionStatus。文章还介绍了@EnabelTransactionManagement注解的工作原理,特别是AutoProxyRegistrar和InfrastructureAdvisorAutoProxyCreator的作用。最后,概述了事务源代码的创建流程,特别是代理对象的生成过程。

一、事务概念:和调用入口说明
1.ACID;
atomicity- 原子性,consistency - 一致性,lsolation- 隔离性,durability - 持久性;
一致性:事务将数据库从一个一致状态转移到另一个一致状态;

2.Spring事务三大接口:
PlatformTransactionManager:事务管理器;通过这个接口,Spring为各个平台如JDBC、Hibernate等都提供对应的事务管理器,但具体的实现由各个平台实现;
TransactionDefinition:事务定义信息(事务隔离级别–传播行为–超时–只读–回滚原则);
TransactionStatus:事务运行状态;

3.@EnabelTransactionManagement 注解详解;
@Import(TransactionManagentConfigurationSelector.class)
–AutoProxyRegistrar -->InfrastructureAdvisorAutoProxyCreator
–ProxyTransactionManagementConfiguration类(3个方法返回值:BeanFactoryTransactionAttributeSourceAdvisor–TransactionAttributeSource–TransactionInterceptor)
3.1:InfrastructureAdvisorAutoProxyCreator 具体分析;Aware接口(代表BeanFactoryAware),InstantiationAwareBeanPostProcessor后置处理器;

1.
/******************** 事务管理器 *******************/
public interface PlatformTransactionManager {
//获取事务的状态
    TransactionStatus getTransaction(TransactionDefinition var1) throws TransactionException;
//事务提交
    void commit(TransactionStatus var1) throws TransactionException;
//事务回滚
    void rollback(TransactionStatus var1) throws TransactionException;
}


/******************** 事务定义信息 *******************/
public interface TransactionDefinition {
//支持当前事物,若当前没有事物就创建一个事物
    int PROPAGATION_REQUIRED = 0;
    //如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行
    int PROPAGATION_SUPPORTS = 1;
    //如果当前存在事务,则加入该事务;如果当前没有事务,则抛出异常
    int PROPAGATION_MANDATORY = 2;
    int PROPAGATION_REQUIRES_NEW = 3;
    int PROPAGATION_NOT_SUPPORTED = 4;
    int PROPAGATION_NEVER = 5;
    int PROPAGATION_NESTED = 6;
    /***
      ** 上面-传播行为
      ** 下面-隔离级别
      **/
    int ISOLATION_DEFAULT = -1;
    int ISOLATION_READ_UNCOMMITTED = 1;
    int ISOLATION_READ_COMMITTED = 2;
    int ISOLATION_REPEATABLE_READ = 4;
    int ISOLATION_SERIALIZABLE = 8;
    //使用默认的超时时间
    int TIMEOUT_DEFAULT = -1;
//获取事务的传播行为
    int getPropagationBehavior();
//获取事务隔离级别
    int getIsolationLevel();
//获取事务超时时间
    int getTimeout();
//返回当前事务是否为只读
    boolean isReadOnly();
//获取事务名称
    String getName();
}

/******************** 事务运行的状态 *******************/
public interface TransactionStatus extends SavepointManager, Flushable {
//是否为新事物
    boolean isNewTransaction();
//是否有保存点
    boolean hasSavepoint();
//设置为只回滚
    void setRollbackOnly();
//是否为只回滚
    boolean isRollbackOnly();

    void flush();
//判断当前事务是否已经完成
    boolean isCompleted();
}
1.@EnableTransactionManagement

2.//通过@Import(.),导入了2. TransactionManagementConfigurationSelector.class
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {

3.public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {

	/**
	 * Returns {@link ProxyTransactionManagementConfiguration} or
	 * {@code AspectJTransactionManagementConfiguration} for {@code PROXY}
	 * and {@code ASPECTJ} values of {@link EnableTransactionManagement#mode()},
	 * respectively.
	 */
	@Override
	protected String[] selectImports(AdviceMode adviceMode) {
		switch (adviceMode) {
		//默认的配置是proxy
			case PROXY:
				return new String[] {AutoProxyRegistrar.class.getName(),
						ProxyTransactionManagementConfiguration.class.getName()};
			case ASPECTJ:
				return new String[] {
						TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME};
			default:
				return null;
		}
	}

}

4.//AutoProxyRegistrar为我们容器注册了一个InfrastructureAdvisorAutoProxyCreator组件
public class AutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
}
public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry) {
        return registerAutoProxyCreatorIfNecessary(registry, (Object)null);
    }

  public static BeanDefinition registerAutoProxyCreatorIfNecessary(BeanDefinitionRegistry registry, Object source) {
        return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
    }

5.public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
    private ConfigurableListableBeanFactory beanFactory;



InfrastructureAdvisorAutoProxyCreator继承图:
在这里插入图片描述

InfrastrureAdvisorAutoProxyCreator:
1.InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator {
    private ConfigurableListableBeanFactory beanFactory;

    public InfrastructureAdvisorAutoProxyCreator() {
    }
//重写父类的
    protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        super.initBeanFactory(beanFactory);
        this.beanFactory = beanFactory;
    }
2.	class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
3.	class AbstractAutoProxyCreator extends ProxyProcessorSupport implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {
4.	interface SmartInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessor {
5.	public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
6.	AbstractAutoProxyCreator 实现了BeanFactoryAware ;但是又马上被AbstractAdvisorAutoProxyCreator 重写; 

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {
    private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper;

    public AbstractAdvisorAutoProxyCreator() {
    }
//重写方法
    public void setBeanFactory(BeanFactory beanFactory) {
        super.setBeanFactory(beanFactory);
        if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
            throw new IllegalArgumentException("AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
        } else {
            this.initBeanFactory((ConfigurableListableBeanFactory)beanFactory);
        }
    }
6.AbstractAdvisorAutoProxyCreator实现了InstantiationAwareBeanPostProcessor 类型的后置处理器;
6.1:

        Object cacheKey = this.getCacheKey(beanClass, beanName);
        if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
            if (this.advisedBeans.containsKey(cacheKey)) {
                return null;
            }

            if (this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }

        if (beanName != null) {
            TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
            if (targetSource != null) {
                this.targetSourcedBeans.add(beanName);
                Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
                Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
                this.proxyTypes.put(cacheKey, proxy.getClass());
                return proxy;
            }
        }

        return null;
    }

6.2:postProcessAfterInstantiation方法
public boolean postProcessAfterInstantiation(Object bean, String beanName) {
        return true;
    }

7.BeanPostProcessor 类型后置处理器,为容器做了什么
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean != null) {
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            if (!this.earlyProxyReferences.contains(cacheKey)) {
                return this.wrapIfNecessary(bean, beanName, cacheKey);
            }
        }

        return bean;
    }

public Object postProcessBeforeInitialization(Object bean,    String beanName) {
        return bean;
    }
ProxyTransactionManagementConfiguration 分析一下:
public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {

public static final String TRANSACTION_ADVISOR_BEAN_NAME =	"org.springframework.transaction.config.internalTransactionAdvisor";
//为我们容器容器中导入internalTransactionAdvisor类型为:BeanFactoryTransactionAttributeSourceAdvisor的增强器		
	@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor() {
		BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
		//设置了事务源属性
		advisor.setTransactionAttributeSource(transactionAttributeSource());
		//设置了事务拦截器
		advisor.setAdvice(transactionInterceptor());
		advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
		return advisor;
	}
//事务属性对象
	@Bean
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public TransactionAttributeSource transactionAttributeSource() {
		return new AnnotationTransactionAttributeSource();
	}

//事务拦截器
	@Bean
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public TransactionInterceptor transactionInterceptor() {
		TransactionInterceptor interceptor = new TransactionInterceptor();
		interceptor.setTransactionAttributeSource(transactionAttributeSource());
		if (this.txManager != null) {
			interceptor.setTransactionManager(this.txManager);
		}
		return interceptor;
	}

}

在这里插入图片描述
在这里插入图片描述
以上源码分析图:在这里插入图片描述

二:事务源代码解析流程
创建源代码过程:InfrastructureAdvisorAutoProxyCreator

1.
/**
 ** 
 **/
 public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        Object cacheKey = this.getCacheKey(beanClass, beanName);
        //判断我们的beanName以及是否处理过
        if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
            if (this.advisedBeans.containsKey(cacheKey)) {
                return null;
            }
//判断当前的bean是不是基础的bean或者直接跳过,不需要代理的
            if (this.isInfrastructureClass(beanClass) || this.shouldSkip(beanClass, beanName)) {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return null;
            }
        }
//判断我们容器中有没有自定义的targetSource 有为我们自动创建对象
//这一步的要求比较高,而且我们正常不会这里创建对象
        if (beanName != null) {
            TargetSource targetSource = this.getCustomTargetSource(beanClass, beanName);
            if (targetSource != null) {
                this.targetSourcedBeans.add(beanName);
                Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
                Object proxy = this.createProxy(beanClass, beanName, specificInterceptors, targetSource);
                this.proxyTypes.put(cacheKey, proxy.getClass());
                return proxy;
            }
        }

        return null;
    }


protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
        if (this.customTargetSourceCreators != null && this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
            TargetSourceCreator[] var3 = this.customTargetSourceCreators;
            int var4 = var3.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                TargetSourceCreator tsc = var3[var5];
                TargetSource ts = tsc.getTargetSource(beanClass, beanName);
                if (ts != null) {
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("TargetSourceCreator [" + tsc + "] found custom TargetSource for bean with name '" + beanName + "'");
                    }

                    return ts;
                }
            }
        }

        return null;
    }

2.InfrastructureAdvisorAutoProxyCreator这个类型作为 后置处理器为我们创建代理对象,实际上是他的父类 AbstractAutoProxyCreator实现了 postProcessAfterInitialization这个接口--AbstractAutoProxyCreator# postProcessAfterInitialization解析
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean != null) {
            Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
            if (!this.earlyProxyReferences.contains(cacheKey)) {
            //当前对象是否需要包装
                return this.wrapIfNecessary(bean, beanName, cacheKey);
            }
        }
        return bean;
    }


protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
//判断代理对象再postProcessAfterInitialization接口中是否被处理过
        if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
            return bean;
        } else if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
            return bean;
            //是否为基础的Bean,或者该对象不应该被调用
        } else if (!this.isInfrastructureClass(bean.getClass()) && !this.shouldSkip(bean.getClass(), beanName)) {
        //获取我们容器中所有的对象
            Object[] specificInterceptors = this.getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, (TargetSource)null);
            //增强器不能为空
            if (specificInterceptors != DO_NOT_PROXY) {
                this.advisedBeans.put(cacheKey, Boolean.TRUE);
                //创建代理对象
                Object proxy = this.createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
                this.proxyTypes.put(cacheKey, proxy.getClass());
                return proxy;
            } else {
                this.advisedBeans.put(cacheKey, Boolean.FALSE);
                return bean;
            }
        } else {
            this.advisedBeans.put(cacheKey, Boolean.FALSE);
            return bean;
        }
    }

/****/
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
//找到合适的增强器
        List<Advisor> advisors = this.findEligibleAdvisors(beanClass, beanName);
        //增强器为空,不需要代理,否则返回增强器
        return advisors.isEmpty() ? DO_NOT_PROXY : advisors.toArray();
    }
    
/****/
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
//获取候选的增强器
        List<Advisor> candidateAdvisors = this.findCandidateAdvisors();
        //从候选器中获取合适的增强器
        List<Advisor> eligibleAdvisors = this.findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
        //对增强器进行扩展
        this.extendAdvisors(eligibleAdvisors);
        //对增强器进行排序
        if (!eligibleAdvisors.isEmpty()) {
            eligibleAdvisors = this.sortAdvisors(eligibleAdvisors);
        }
        return eligibleAdvisors;
    }

/*****/
 protected List<Advisor> findCandidateAdvisors() {
 //通过我们的增强器探测工具找
        return this.advisorRetrievalHelper.findAdvisorBeans();
    }
    
public List<Advisor> findAdvisorBeans() {
//先从缓存中获取
        String[] advisorNames = this.cachedAdvisorBeanNames;
        if (advisorNames == null) {
        //去容器中查找实现了我们Advisor接口的实现类 的名称:(org.springframework.transaction.config.internalTransactionAdvisor 类型为BeanFactoryTransactionAttributeSourceAdvisor)
            advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Advisor.class, true, false);
            //放入到缓存
            this.cachedAdvisorBeanNames = advisorNames;
        }

        if (advisorNames.length == 0) {
            return new ArrayList();
        } else {
            List<Advisor> advisors = new ArrayList();
            String[] var3 = advisorNames;
            int var4 = advisorNames.length;
//循环我们的增强器
            for(int var5 = 0; var5 < var4; ++var5) {
                String name = var3[var5];
                //判断是否合适的
                if (this.isEligibleBean(name)) {
                //当前的增强器是不是正在创建的
                    if (this.beanFactory.isCurrentlyInCreation(name)) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Skipping currently created advisor '" + name + "'");
                        }
                    } else {
                        try {
                        //通过getBean的显示调用获取BeanFactoryTransactionAttributeSourceAdvisor 组件
                            advisors.add(this.beanFactory.getBean(name, Advisor.class));
                        } catch (BeanCreationException var10) {
                            Throwable rootCause = var10.getMostSpecificCause();
                            if (rootCause instanceof BeanCurrentlyInCreationException) {
                                BeanCreationException bce = (BeanCreationException)rootCause;
                                if (this.beanFactory.isCurrentlyInCreation(bce.getBeanName())) {
                                    if (logger.isDebugEnabled()) {
                                        logger.debug("Skipping advisor '" + name + "' with dependency on currently created bean: " + var10.getMessage());
                                    }
                                    continue;
                                }
                            }

                            throw var10;
                        }
                    }
                }
            }

            return advisors;
        }
    }

/**
 **判断包含是否为合适的最终逻辑 * 容器中的bean定义包含当前的增强器的bean定义,且bean的role是int ROLE_INFRASTRUCTURE = 2;
 **/
protected boolean isEligibleAdvisorBean(String beanName) {
        return this.beanFactory.containsBeanDefinition(beanName) && this.beanFactory.getBeanDefinition(beanName).getRole() == 2;
    }

/****/
protected List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {
        ProxyCreationContext.setCurrentProxiedBeanName(beanName);

        List var4;
        try {
        //真正去候选的增强器中找到能用的增强器
            var4 = AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
        } finally {
            ProxyCreationContext.setCurrentProxiedBeanName((String)null);
        }

        return var4;
    }

/****/
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
//判断传入进来的增强器为空则直接返回
        if (candidateAdvisors.isEmpty()) {
            return candidateAdvisors;
        } else {
        //创建一个本类能用的增强器集合
            List<Advisor> eligibleAdvisors = new LinkedList();
            Iterator var3 = candidateAdvisors.iterator();
//循环增强器
            while(var3.hasNext()) {
                Advisor candidate = (Advisor)var3.next();
                //判断增强器是不是实现了IntroductionAdvisor 很明显没实现该接口
                if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
                //添加能用的增强器
                    eligibleAdvisors.add(candidate);
                }
            }

            boolean hasIntroductions = !eligibleAdvisors.isEmpty();
            Iterator var7 = candidateAdvisors.iterator();

            while(var7.hasNext()) {
                Advisor candidate = (Advisor)var7.next();
                if (!(candidate instanceof IntroductionAdvisor) && canApply(candidate, clazz, hasIntroductions)) {
                    eligibleAdvisors.add(candidate);
                }
            }

            return eligibleAdvisors;
        }
    }

/****/
public static boolean canApply(Advisor advisor, Class<?> targetClass, boolean hasIntroductions) {
////根据类的继承图 发现 BeanFactoryTransactionAttributeSourceAdvisor没实现IntroductionAdvisor接口
        if (advisor instanceof IntroductionAdvisor) {
            return ((IntroductionAdvisor)advisor).getClassFilter().matches(targetClass);
            //BeanFactoryTransactionAttributeSourceAdvisor实现了PointcutAdvisor接口
        } else if (advisor instanceof PointcutAdvisor) {
        //强制转换为PointcutAdvisor
            PointcutAdvisor pca = (PointcutAdvisor)advisor;
            return canApply(pca.getPointcut(), targetClass, hasIntroductions);
        } else {
            return true;
        }
    }

/**判断当前增强器是否为本来能用的	**/
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
        Assert.notNull(pc, "Pointcut must not be null");
        if (!pc.getClassFilter().matches(targetClass)) {
            return false;
        } else {
        //获取切点中的方法匹配器 TransactionAttributeSourcePointcut
        //该切点在创建BeanFactoryTransactionAttributeSourceAdvisor的时候 创建了切点TransactionAttributeSourcePointcut
            MethodMatcher methodMatcher = pc.getMethodMatcher();
            if (methodMatcher == MethodMatcher.TRUE) {
                return true;
            } else {
                IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
                //判断方法匹配器是不是IntroductionAwareMethodMatcher
                if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
                    introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher)methodMatcher;
                }
//获取当前类实现接口类型
                Set<Class<?>> classes = new LinkedHashSet(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
                classes.add(targetClass);
                Iterator var6 = classes.iterator();
//循环上一步的接口类型
                while(var6.hasNext()) {
                    Class<?> clazz = (Class)var6.next();
                    //获取接口所有方法
                    Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
                    Method[] var9 = methods;
                    int var10 = methods.length;
//循环我们接口中的方法
                    for(int var11 = 0; var11 < var10; ++var11) {
                        Method method = var9[var11];
                        //正在进行匹配的是methodMatcher.matches(method, targetClass)这个逻辑
                        if (introductionAwareMethodMatcher != null && introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions) || methodMatcher.matches(method, targetClass)) {
                            return true;
                        }
                    }
                }

                return false;
            }
        }
    }

/**org.springframework.transaction.interceptor.TransactionAttributeSourcePointcut#matches**/
public boolean matches(Method method, Class<?> targetClass) {
		if (targetClass != null && TransactionalProxy.class.isAssignableFrom(targetClass)) {
			return false;
		}
		//获取我们的事物源对象(在ProxyTransactionManagementConfiguration配置类配置的这里获取)
		TransactionAttributeSource tas = getTransactionAttributeSource();
		//从事务源中获取事务属性
		return (tas == null || tas.getTransactionAttribute(method, targetClass) != null);
	}

/**获取事务属性 **/
public TransactionAttribute getTransactionAttribute(Method method, Class<?> targetClass) {
		if (method.getDeclaringClass() == Object.class) {
			return null;
		}

		// 通过目标类和目标类的接口方法 拼接缓存key
		Object cacheKey = getCacheKey(method, targetClass);
		//去缓存中获取
		TransactionAttribute cached = this.attributeCache.get(cacheKey);
		if (cached != null) {
			// ,
			//缓存中有,直接返回就行
			if (cached == NULL_TRANSACTION_ATTRIBUTE) {
				return null;
			}
			else {
				return cached;
			}
		}
		else {
			//计算事务的属性
			TransactionAttribute txAttr = computeTransactionAttribute(method, targetClass);
			//若事务属性为空
			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.isDebugEnabled()) {
					logger.debug("Adding transactional method '" + methodIdentification + "' with attribute: " + txAttr);
				}
				//加入到缓存中
				this.attributeCache.put(cacheKey, txAttr);
			}
			return txAttr;
		}
	}


/**计算事务的属性**/
protected TransactionAttribute computeTransactionAttribute(Method method, Class<?> targetClass) {
		//判断方法的修饰符
		if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
			return null;
		}

		//忽略cglib的代理
		Class<?> userClass = ClassUtils.getUserClass(targetClass);
		//method为接口中的方法,specificMethod为我们实现类方法
		Method specificMethod = ClassUtils.getMostSpecificMethod(method, userClass);
		// If we are dealing with method with generic parameters, find the original method.
		specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

		//找我们【实现类】中的【方法】上的事物属性
		TransactionAttribute txAttr = findTransactionAttribute(specificMethod);
		if (txAttr != null) {
			return txAttr;
		}

		// 【方法所在类】上有没有事物属性
		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;
			}
			//【接口上】
			txAttr = findTransactionAttribute(method.getDeclaringClass());
			if (txAttr != null && ClassUtils.isUserLevelMethod(method)) {
				return txAttr;
			}
		}

		return null;
	}
/**从方法上找事物属性对象**/
protected TransactionAttribute findTransactionAttribute(Method method) {
		return determineTransactionAttribute(method);
	}
/****/
protected TransactionAttribute determineTransactionAttribute(AnnotatedElement element) {
//获取方法上的注解
		if (element.getAnnotations().length > 0) {
		//事物注解解析器
			for (TransactionAnnotationParser annotationParser : this.annotationParsers) {
			//解析我们的注解
				TransactionAttribute attr = annotationParser.parseTransactionAnnotation(element);
				if (attr != null) {
					return attr;
				}
			}
		}
		return null;
	}

/**
 ** 解析我们的注解org.springframework.transaction.annotation.SpringTransactionAnnotationParser#parseTransactionAnnotation
  **/
  public TransactionAttribute parseTransactionAnnotation(AnnotatedElement element) {
  //解析@Transactional属性对象
		AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(
				element, javax.transaction.Transactional.class);
		if (attributes != null) {
		//真正的解析@Transactional属性
			return parseTransactionAnnotation(attributes);
		}
		else {
			return null;
		}
	}
	
/***解析事物注解*/
protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) {
		RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute();

//传播行为
		Propagation propagation = attributes.getEnum("propagation");
		rbta.setPropagationBehavior(propagation.value());
		Isolation isolation = attributes.getEnum("isolation");
		//隔离级别
		rbta.setIsolationLevel(isolation.value());
		//事务超时
		rbta.setTimeout(attributes.getNumber("timeout").intValue());
		//事务是否只读
		rbta.setReadOnly(attributes.getBoolean("readOnly"));
		//事务的名称
		rbta.setQualifier(attributes.getString("value"));

		List<RollbackRuleAttribute> rollbackRules = new ArrayList<RollbackRuleAttribute>();
		//事务回滚规则
		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;
	}

源码流程调用流程图,代码如上
在这里插入图片描述

  1. 真正创建代理对象的是 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator # createProxy
protected Object createProxy(Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
//暴露代理对象
        if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
         AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory)this.beanFactory, beanName, beanClass);
        }
//创建代理工厂
        ProxyFactory proxyFactory = new ProxyFactory();
        proxyFactory.copyFrom(this);
        //判断CGLIB代理还是JDK代理
        if (!proxyFactory.isProxyTargetClass()) {
            if (this.shouldProxyTargetClass(beanClass, beanName)) {
                proxyFactory.setProxyTargetClass(true);
            } else {
                this.evaluateProxyInterfaces(beanClass, proxyFactory);
            }
        }
//把合适的拦截器转换为增强器
        Advisor[] advisors = this.buildAdvisors(beanName, specificInterceptors);
        proxyFactory.addAdvisors(advisors);
        proxyFactory.setTargetSource(targetSource);
        this.customizeProxyFactory(proxyFactory);
        proxyFactory.setFrozen(this.freezeProxy);
        if (this.advisorsPreFiltered()) {
            proxyFactory.setPreFiltered(true);
        }
//真正的创建代理对象
        return proxyFactory.getProxy(this.getProxyClassLoader());
    }
/****/
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (!config.isOptimize() && !config.isProxyTargetClass() && !this.hasNoUserSuppliedProxyInterfaces(config)) {
            return new JdkDynamicAopProxy(config);
        } else {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: Either an interface or a target is required for proxy creation.");
            } else {
            //判断是接口还是代理,穿件CGLIB代理或者JDK代理
                return (AopProxy)(!targetClass.isInterface() && !Proxy.isProxyClass(targetClass) ? new ObjenesisCglibAopProxy(config) : new JdkDynamicAopProxy(config));
            }
        }
    }
/**JDK代理**/
public Object getProxy(ClassLoader classLoader) {
        if (logger.isDebugEnabled()) {
            logger.debug("Creating JDK dynamic proxy: target source is " + this.advised.getTargetSource());
        }

        Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
        this.findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
        return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this);
    }

createBean:
resolveBeforeInstantiation–入口

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
		Object bean = null;
		if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
			// Make sure bean class is actually resolved at this point.
			//判断是否是InstantiationAwareBeanPostProcessors类型
			if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
				Class<?> targetType = determineTargetType(beanName, mbd);
				if (targetType != null) {
				//before方法
					bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
					if (bean != null) {
					//after方法
						bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
					}
				}
			}
			mbd.beforeInstantiationResolved = (bean != null);
		}
		return bean;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值