深圳惠源办公设备租赁
联系电话 :13713619827

Spring源码解析(三)-Spring事务原理分析

1
发表时间:2021-11-11 22:55

Spring源码解析


前言

该部分需要了解Spring事务的基本概念-切面
SpringBoot以@EnableTransactionManagement注解启动事务管理,所以我们从EnableTransactionManagement开始分析。


一、EnableTransactionManagement

1、EnableTransactionManagement

如下可以看到EnableTransactionManagement引入了注解@Import,Import的作用可以看下SpringBoot源码解析二,可以添加Bean定义,接下来看下TransactionManagementConfigurationSelector
在这里插入图片描述

2、TransactionManagementConfigurationSelector

默认代理有JDK代理和ASPETJ两种方式,我们分析JDK代理
在这里插入图片描述JDK代理引入了AutoProxyRegistrar和ProxyTransactionManagementConfiguration

3、AutoProxyRegistrar

在这里插入图片描述

3.1 registerAutoProxyCreatorIfNecessary-往容器加InfrastructureAdvisorAutoProxyCreator的Bean定义

在这里插入图片描述

private static BeanDefinition registerOrEscalateApcAsRequired(Class<?> cls, BeanDefinitionRegistry registry, @Nullable Object source) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");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;}

3.2、InfrastructureAdvisorAutoProxyCreator继承结构

分析InfrastructureAdvisorAutoProxyCreator的继承结构,发现其父类有实现BeanPostProcessor(这一点很重要,从这里入口对Bean进行代理而实现事务)
在这里插入图片描述

4、ProxyTransactionManagementConfiguration

从类名可以看出是事务配置类,为事务注入切面BeanFactoryTransactionAttributeSourceAdvisor,事务切面包含了TransactionInterceptor事务处理器拦截器,事务在该类处理

// 切面BeanFactoryTransactionAttributeSourceAdvisor@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)@Role(BeanDefinition.ROLE_INFRASTRUCTURE)public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(TransactionAttributeSource transactionAttributeSource,TransactionInterceptor transactionInterceptor) {BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
		advisor.setTransactionAttributeSource(transactionAttributeSource);
		advisor.setAdvice(transactionInterceptor);if (this.enableTx != null) {
			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(TransactionAttributeSource transactionAttributeSource) {TransactionInterceptor interceptor = new TransactionInterceptor();
		interceptor.setTransactionAttributeSource(transactionAttributeSource);if (this.txManager != null) {
			interceptor.setTransactionManager(this.txManager);}return interceptor;}>

第一阶段小总结:EnableTransactionManagement为我们准备好了事务,生成事务代理对象的入口-InfrastructureAdvisorAutoProxyCreator,事务切面-BeanFactoryTransactionAttributeSourceAdvisor

二、怎么进入InfrastructureAdvisorAutoProxyCreator入口,生成代理对象

上节分析了invokeBeanFactoryPostProcessors-执行实现了postProcessBeanFactory的类的postProcessBeanFactory方法,这节继续分析registerBeanPostProcessors-将BeanPostProcessors注入到Bean工厂
在这里插入图片描述

1.注册BeanPostProcessors到Bean工厂

public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {// 获取所有实现了BeanPostProcessor的Bean的名称String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));// 获取所有继承了PriorityOrdered的BeanPostProcessors // 排序List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();List<String> orderedPostProcessorNames = new ArrayList<>();List<String> nonOrderedPostProcessorNames = new ArrayList<>();for (String ppName : postProcessorNames) {if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {
					internalPostProcessors.add(pp);}}else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);}else {
				nonOrderedPostProcessorNames.add(ppName);}}// 第一, 注册实现了PriorityOrdered的BeanPostProcessorssortPostProcessors(priorityOrderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);// 接下来, 注册实现了Ordered的BeanPostProcessorsList<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());for (String ppName : orderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);}}sortPostProcessors(orderedPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, orderedPostProcessors);// 然后, 注册剩余的常规的BeanPostProcessors.List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());for (String ppName : nonOrderedPostProcessorNames) {BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);}}registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);// Finally, re-register all internal BeanPostProcessors.sortPostProcessors(internalPostProcessors, beanFactory);registerBeanPostProcessors(beanFactory, internalPostProcessors);// Re-register post-processor for detecting inner beans as ApplicationListeners,// moving it to the end of the processor chain (for picking up proxies etc).
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));}

2、 BeanPostProcessors的执行

Spring在getBean的时候会去执行BeanPostProcessors的方法,getBean后续分析,我们直接进入执行BeanPostProcessors

/**
	 * 创建Bean实例
	 * @see #doCreateBean
	 */@Overrideprotected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)throws BeanCreationException {try {// 给BeanPostProcessors一个机会去返回代理对象,就是这里啦Object bean = resolveBeforeInstantiation(beanName, mbdToUse);if (bean != null) {return bean;}}catch (Throwable ex) {throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,"BeanPostProcessor before instantiation of bean failed", ex);}try {Object beanInstance = doCreateBean(beanName, mbdToUse, args);if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");}return beanInstance;}catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {// A previously detected exception with proper bean creation context already,// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.throw ex;}catch (Throwable ex) {throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);}}

3、执行InfrastructureAdvisorAutoProxyCreator的postProcessBeforeInstantiation()方法

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;}// protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);if (result != null) {return result;}}}return null;}

4、创建代理对象
JDK代理JdkDynamicAopProxy
Cglib代理为CglibAopProxy

public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {Object cacheKey = getCacheKey(beanClass, beanName);// 判断是否需要创建代理对象if (!StringUtils.hasLength(beanName) || !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;}}TargetSource targetSource = getCustomTargetSource(beanClass, beanName);if (targetSource != null) {if (StringUtils.hasLength(beanName)) {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;}

总结

以上就是Spring事务代理对象的创建过程

分享到:
产品推荐 理光mpC6001/5504/4504数码复印机 理光mpC5503/4503数码复印机 理光mpC3503/3303
服务支持


厂家直接供货
24小时客户服务
办公方案支持
名字:
*
邮箱:
*
电话:
*
留言:
*
验证码
 换一张
*
提交留言
在线留言 :
会员登录
登录
其他帐号登录:
留言
回到顶部