In-depth analysis of Spring AOP source code: A few annotations can control transactions? Is there such a magic?


Declarative transaction is very convenient, especially pure annotation mode, only a few annotations can control the transaction

Thinking: What did these annotations do? so amazing!

@EnableTransactionManagement @Transactional

一、@EnableTransactionManagement

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {
    
    

}

@EnableTransactionManagementThe annotation is referenced with the @Import tagTransactionManagementConfigurationSelector类 , and this class imports two important components into the container


This article refers to "Spring Advanced Source Notes", students who need to add assistant VX: C18173184271,备注一下CSDN+工作年限!get it for free

Two, load the transaction control component

  • AutoProxyRegistrar
    AutoProxyRegistrar 类The registerBeanDefinitions method , it also registered a component

    into the AopConfigUtils.registerAutoProxyCreatorIfNecessarymethod

    found eventually, registered the called InfrastructureAdvisorAutoProxyCreatorof Bean, and this class is a AbstractAutoProxyCreatorsubclass implements SmartInstantiationAwareBeanPostProcessor Interface
public class InfrastructureAdvisorAutoProxyCreator extends
AbstractAdvisorAutoProxyCreator

public abstract class AbstractAdvisorAutoProxyCreator extends
AbstractAutoProxyCreator

public abstract class AbstractAutoProxyCreator extends
ProxyProcessorSupport
 	implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware

Inheritance architecture diagram below

it implements SmartInstantiationAwareBeanPostProcessor, stated that this is a post-processor, but with spring AOPopen @EnableAspectJAutoProxyregistration at the time of AnnotationAwareAspectJProxyCreatorimplementation is the same interface, so that the declarative transaction is springAOPan application thought

  • ProxyTransactionManagementConfiguration Component
/*
* Copyright 2002-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.transaction.annotation;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.transaction.config.TransactionManagementConfigUtils;
import org.springframework.transaction.interceptor.BeanFactoryTransactionAttribut eSourceAdvisor;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

/**
* {@code @Configuration} class that registers the Spring infrastructure
beans
* necessary to enable proxy-based annotation-driven transaction
management.
*
* @author Chris Beams
* @since 3.1
* @see EnableTransactionManagement
* @see TransactionManagementConfigurationSelector
*/
@Configuration
public class ProxyTransactionManagementConfiguration extends
AbstractTransactionManagementConfiguration {
    
    
 
 	@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
 	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
 	public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(){
    
    
 		// 事务增强器
 		BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
 		// 向事务增强器中注入 属性解析器 transactionAttributeSource
 		advisor.setTransactionAttributeSource(transactionAttributeSource());
 		// 向事务增强器中注入 事务拦截器 transactionInterceptor
 		advisor.setAdvice(transactionInterceptor());
 		if (this.enableTx != null) {
    
    
 			advisor.setOrder(this.enableTx.<Integer>getNumber("order"));
 		}
 		return advisor;
 	}
 	
 	@Bean
 	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
 	// 属性解析器 transactionAttributeSource
 	public TransactionAttributeSource transactionAttributeSource() {
    
    
 		return new AnnotationTransactionAttributeSource();
 	}
	@Bean
 	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
 	// 事务拦截器 transactionInterceptor
 	public TransactionInterceptor transactionInterceptor() {
    
    
 		TransactionInterceptor interceptor = new TransactionInterceptor();
 
		interceptor.setTransactionAttributeSource(transactionAttributeSource());
 		if (this.txManager != null) {
    
    
 			interceptor.setTransactionManager(this.txManager);
 		}
 		return interceptor;
 	} 
}

ProxyTransactionManagementConfigurationConfiguration class is a container, a component register transactionAdvisor, called transaction booster , then the transaction enhancer has injected two properties: transactionAttributeSource, i.e. attributes the parser transactionAttributeSource and transaction interceptors transactionInterceptor

  • Attribute parser AnnotationTransactionAttributeSource part of the source code is as follows


Property parser variable is a member annotationParsers, is a collection, you can add a variety of annotation parser
( TransactionAnnotationParser), we are concerned about the Spring annotation parser, some source code as

one of the role attribute parser is used to parse @Transaction comment

  • TransactionInterceptor Transaction interceptor, part of the source code is as follows

  • How are the above components related?
    • Transaction interceptor implements MethodInterceptor interfaces , retrospective look at the above-mentioned InfrastructureAdvisorAutoProxyCreatorpost-processor, it will get its interceptor chain when the proxy object method of execution of the target, while the interceptor is this chain TransactionInterceptor, which links these two components stand up;
    • The construction method is passed in PlatformTransactionManager( transaction manager ) and TransactionAttributeSource( attribute parser ), but trace ProxyTransactionManagementConfigurationthe source code posted above , when registering the transaction interceptor, this construction method with parameters is not called, but the construction method without parameters is called. Then call the set method to inject these two properties, the effect is the same.
  • invokeWithinTransaction Method, part of the source code is as follows (pay attention to the labels 1, 2, 3, 4)


If you need this full version 《Spring高级源码笔记》, you only need to support me in this article.

A lot of support, you can get information for free-after three consecutive years (promise: 100% free)

Quick start channel: add assistant VX: C18173184271,备注一下CSDN+工作年限!get it for free! Full of sincerity! ! !

Guess you like

Origin blog.csdn.net/Java_Caiyo/article/details/113180674