【Spring系列】Spring事务

我们通过Debug Spring IOC的启动流程来看Spring的事务管理。

第一阶段:初始化BeanPostProcessor: AnnotationAwareAspectJAutoProxyCreator

先进入Spring启动的核心流程AbstractApplicationContext的refresh方法,

定位到第二步:初始化BeanFactory

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        prepareRefresh();

        // 第二步:初始化BeanFactory, 加载工程的xml配置文件定义的Bean
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// 第三步:Prepare the bean factory for use in this context.
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			initMessageSource();

			// Initialize event multicaster for this context.
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			onRefresh();

			// Check for listener beans and register them.
			registerListeners();

			// 第十一步:实例化@Service
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			finishRefresh();
		} catch (BeansException ex) {
			// 省略
		} finally {
			// 省略
		}
	}
}

进入第二步,看源码:

@Override
protected final void refreshBeanFactory() throws BeansException {
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
        // 创建BeanFactory
		DefaultListableBeanFactory beanFactory = createBeanFactory();
		beanFactory.setSerializationId(getId());
		customizeBeanFactory(beanFactory);
        // 解析并加载xml中的Bean
		loadBeanDefinitions(beanFactory);
		synchronized (this.beanFactoryMonitor) {
		    this.beanFactory = beanFactory;
		}
	} catch (IOException ex) {
		// 省略
	}
}

在loadBeanDefinitions方法加载xml配置的时候,如果配置了解析xml文件的时候,NamespaceHandlerSupport的parse方法查找解析器:

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
	return findParserForElement(element, parserContext).parse(element, parserContext);
}

找到的解析器为:AspectJAutoProxyBeanDefinitionParser,开始解析:

@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
    // 会获取到AnnotationAwareAspectJAutoProxyCreator BeanDefinition注册到BeanFactory的beanDefinitionMap中去
	AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element);
	extendBeanDefinition(element, parserContext);
	return null;
}

通过上面分析可知,在Spring启动初始化BeanFactory加载xml配置的时候会把AnnotationAwareAspectJAutoProxyCreator放到BeanFactory的beanDefinitionMap中。

第二阶段:初始化Service, 创建代理

进入Spring启动的第十一步:实例化

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // 省略...

    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    beanFactory.freezeConfiguration();

    // 实例化
    beanFactory.preInstantiateSingletons();
}
preInstantiateSingletons方法getBean实例化:
@Override
public void preInstantiateSingletons() throws BeansException {
    // ...
	
    List beanNames = new ArrayList(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            if (isFactoryBean(beanName)) {
	    	    // 省略...
                if (isEagerInit) {
                    getBean(beanName);
                }
            } else {
                getBean(beanName);
            }
        }
    }
    // 省略
}

getBean方法:

@Override
public Object getBean(String name) throws BeansException {
	return doGetBean(name, null, null, false);
}
protected  T doGetBean(final String name, final Class requiredType, final Object[] args, boolean typeCheckOnly)
    // 省略。。。

    // 第一次获取不到sharedInstance
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        // 省略。。。
    } else {    

        // 核心步骤: bean instance.
        if (mbd.isSingleton()) {
            sharedInstance = getSingleton(beanName, new ObjectFactory() {
                @Override
                public Object getObject() throws BeansException {
                    try {
                        return createBean(beanName, mbd, args);
                    } catch (BeansException ex) {
                        // 省略
                    }
                }
            });
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
        } else if (mbd.isPrototype()) {
            // It's a prototype -> create a new instance.
            Object prototypeInstance = null;
            try {
                beforePrototypeCreation(beanName);
                prototypeInstance = createBean(beanName, mbd, args);
            } finally {
                afterPrototypeCreation(beanName);
            }
            bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
        } else {
		    //
        }
    }
    // 省略。。。
    return (T) bean;
} 
  

进入createBean方法:

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
		
	RootBeanDefinition mbdToUse = mbd;

	// 若bean definition 没有BeanClass, 则设置 beanClass
	Class resolvedClass = resolveBeanClass(mbd, beanName);
	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
		mbdToUse = new RootBeanDefinition(mbd);
		mbdToUse.setBeanClass(resolvedClass);
	}

	// Prepare method overrides.
	try {
		mbdToUse.prepareMethodOverrides();
	} catch (BeanDefinitionValidationException ex) {
		// ..
	}

	try {
        // 给BeanPostProcessors机会,优先创建代理
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    } catch (Throwable ex) {

    }
    // 如果没有创建代理,则实例化
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
	
    return beanInstance;
}

来看看BeanPostProcessor怎么创建代理:

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.
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			Class targetType = determineTargetType(beanName, mbd);
			if (targetType != null) {
				bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
				if (bean != null) {
					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
				}
			}
		}
		mbd.beforeInstantiationResolved = (bean != null);
	}
	return bean;
}

applyBeanPostProcessorsBeforeInstantiation会触发BeanPostProcessor的postProcessBeforeInstantiation方法,因为AnnotationAwareAspectJAutoProxyCreator是BeanPostProcessor,所以AnnotationAwareAspectJAutoProxyCreator也会工作。来看看AnnotationAwareAspectJAutoProxyCreator的postProcessBeforeInstantiation方法(继承自AbstractAutoProxyCreator):

@Override
public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
	Object cacheKey = getCacheKey(beanClass, beanName);

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

	// Create proxy here if we have a custom TargetSource.
	// Suppresses unnecessary default instantiation of the target bean:
	// The TargetSource will handle target instances in a custom fashion.
	if (beanName != null) {
		TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
		if (targetSource != null) {
			this.targetSourcedBeans.add(beanName);
			Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
			Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;
		}
	}

	return null;
}

 如果返回null,进入doCreateBean方法

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException {

	// Instantiate the bean.
	BeanWrapper instanceWrapper = null;
	if (mbd.isSingleton()) {
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	if (instanceWrapper == null) {
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
	Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
	mbd.resolvedTargetType = beanType;

	// Allow post-processors to modify the merged bean definition.
	synchronized (mbd.postProcessingLock) {
		if (!mbd.postProcessed) {
			try {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
			} catch (Throwable ex) {
				//
			}
			mbd.postProcessed = true;
		}
	}

	// Eagerly cache singletons to be able to resolve circular references
	// even when triggered by lifecycle interfaces like BeanFactoryAware.
	boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
	if (earlySingletonExposure) {
		
		addSingletonFactory(beanName, new ObjectFactory() {
			@Override
			public Object getObject() throws BeansException {
                // 在实例化的时候,在getSingleton中调用(从SingletonFactory获取ObjectFactory然后调用)
				return getEarlyBeanReference(beanName, mbd, bean);
			}
		});
	}

	// Initialize the bean instance.
	Object exposedObject = bean;
	try {
        // @Autowird 和 @Value 注入, 可能会进行实例化doGetBean
		populateBean(beanName, mbd, instanceWrapper);
		if (exposedObject != null) {
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
	} catch (Throwable ex) {
		// 。。。
	}

	if (earlySingletonExposure) {
		// ...
	}

	// Register bean as disposable.
	try {
		registerDisposableBeanIfNecessary(beanName, bean, mbd);
	} catch (BeanDefinitionValidationException ex) {
			//
	}

	return exposedObject;
} 
  

getSingleton 通过SingletonFactory 获取ObjectFactory,调用ObjectFactory.getObject, 从而调用到getEarlyBeanReferance,最后到AnnotationAwareAspectJAutoProxyCreator的getEarlyBeanReferance方法。

@Override
public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
	Object cacheKey = getCacheKey(bean.getClass(), beanName);
	if (!this.earlyProxyReferences.contains(cacheKey)) {
		this.earlyProxyReferences.add(cacheKey);
	}
	return wrapIfNecessary(bean, beanName, cacheKey);
}

wrapIfNecessary方法创建事务的代理

protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
	if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
		return bean;
	}
	if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
		return bean;
	}
	if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
		this.advisedBeans.put(cacheKey, Boolean.FALSE);
		return bean;
	}

	// Create proxy if we have advice.
	Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
	if (specificInterceptors != DO_NOT_PROXY) {
		this.advisedBeans.put(cacheKey, Boolean.TRUE);
		Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
		this.proxyTypes.put(cacheKey, proxy.getClass());
		return proxy;
	}

	this.advisedBeans.put(cacheKey, Boolean.FALSE);
	return bean;
}

进入getAdvicesAndAdvisorsForBean(即AbstractAdvisorAutoProxyCreator的getAdvicesAndAdvisorsForBean方法):

@Override
protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) {
    List advisors = findEligibleAdvisors(beanClass, beanName);
    if (advisors.isEmpty()) {
        return DO_NOT_PROXY;
    }
    return advisors.toArray();
}
protected List findEligibleAdvisors(Class beanClass, String beanName) {
    List candidateAdvisors = findCandidateAdvisors();
    // 这里面会判断类的方法是否有@Transactional注解
    List eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
    extendAdvisors(eligibleAdvisors);
    if (!eligibleAdvisors.isEmpty()) {
        eligibleAdvisors = sortAdvisors(eligibleAdvisors);
    }
    return eligibleAdvisors;
}

 

你可能感兴趣的:(Spring源码系列)