• Now that you’ve learned about Spring AOP principles and the basics of transactions, let’s talk about how Spring handles transactions at the bottom. If you are reading this article and are not familiar with Spring AOP principles, it is recommended to read my article: Spring AOP Principles: I’ll use my prioristic powers to help you thoroughly understand the principles of @enableAspectJAutoProxy AOP annotations. The rest of the article will be relevant to this article.

What are a, say first @ EnableTransactionManagement annotation internal method

  • We look at the source of the @ EnableTransactionManagement annotation:

    public @interface EnableTransactionManagement {
    	// Ignore comments
    	boolean proxyTargetClass(a) default false;
    	// Ignore comments
    	AdviceMode mode(a) default AdviceMode.PROXY;
    	// Ignore comments
    	int order(a) default Ordered.LOWEST_PRECEDENCE;
    Copy the code

    It has three main methods, and each method has a default value. Normally, we use the @ EnableTransactionManagement comment, will not be additional internal methods return values specified, use the default values. So what exactly does the return value of these three methods do? See below:

    We’ll talk about when that happens.

Second, chat again @ EnableTransactionManagement annotations in the underlying what have you done now

  • Routines like @ EnableAspectJAutoProxy notes, is to the Spring to import a TransactionManagementConfigurationSelector components, it belongs to ImportSelector type. Let’s look at the source code:

    public class TransactionManagementConfigurationSelector extends AdviceModeImportSelector<EnableTransactionManagement> {
    	protected String[] selectImports(AdviceMode adviceMode) {
             / / the adviceMode is when we use the @ EnableTransactionManagement comment internal model () method returns a value
             / / we don't have to use @ EnableTransactionManagement annotations within the return values of all methods, therefore, the adviceMode here
             // The value is "PROXY"
    		switch (adviceMode) {
    			case PROXY:
                      // Finally this code will execute, adding two beans to the Spring container:
                      / / AutoProxyRegistrar and ProxyTransactionManagementConfiguration
                      / / to understand the underlying principles of the Spring, it now depends on AutoProxyRegistrar and ProxyTransactionManagementConfiguration cough up
    				return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()};
    			case ASPECTJ:
    				return new String[] {TransactionManagementConfigUtils.TRANSACTION_ASPECT_CONFIGURATION_CLASS_NAME};
    				return null; }}}Copy the code

2.1 AutoProxyRegistrar

  • Let’s first look at what type it is:

    According to class inheritance diagram shows that it belongs to ImportBeanDefinitionRegistrar type, the Spring will eventually call internal registerBeanDefinitions method, the following is a key in source code:

    if (mode == AdviceMode.PROXY) {
        if ((Boolean) proxyTargetClass) {
            return; }}Copy the code

    Above has said, when we use the @ EnableTransactionManagement comment, did not have to modify the internal methods return values. So, mode here is advicemode.proxy and proxyTargetClass is false. Conclusion by the source logic: the Spring will eventually perform this code: AopConfigUtils. RegisterAutoProxyCreatorIfNecessary (registry); And the main function of this code is to add the Spring container bean: InfrastructureAdvisorAutoProxyCreator. So what are we supposed to do next? Yes, it’s time the bean (InfrastructureAdvisorAutoProxyCreator) what kind of work.

2.1.1 InfrastructureAdvisorAutoProxyCreator role

  • Similarly, let’s look at its inheritance diagram first:

    Let’s focus on the classes in the red box in the diagram. Then we could look at the inside the annotations enable Spring AOP @ EnableAspectJAutoProxy imported AnnotationAwareAspectJAutoProxyCreator bean class diagram:

    They all implement the same public abstract class AbstractAutoProxyCreator. What does that mean? This shows that as long as AnnotationAwareAspectJAutoProxyCreator and InfrastructureAdvisorAutoProxyCreator internal not to do any AbstractAutoProxyCreator the abstract parent class Method rewrite, then they will have AbstractAutoProxyCreator functionality. In fact, they did not rewrite any methods within AbstractAutoProxyCreator. Spring AOP Principles: I’ll use my prehistoric powers to help you thoroughly understand the principles of @enableAspectJAutoProxy AOP annotations as mentioned in the article, The Spring AOP for section, section, notice is the process of this method InstantiationAwareBeanPostProcessor# postProcessBeforeInstantiation credit, And generate the AOP proxy objects is BeanPostProcessor# postProcessAfterInitialization of credit. These functions of finding sections and generating proxy objects are actually functions of the abstract parent AbstractAutoProxyCreator. Therefore, our InfrastructureAdvisorAutoProxyCreator had the finding section, section, the function of notification, and generate a proxy object.

2.1.2 summary

  • The AutoProxyRegistrar role is represented as follows:

2.2 ProxyTransactionManagementConfiguration looks like

  • As usual, look at the class inheritance diagram:

    This class is simpler and uses some of Spring’s extension points, although its parent class also builds some Spring components. But in the end is ProxyTransactionManagementConfiguration internal builds a bean named BeanFactoryTransactionAttributeSourceAdvisor. ProxyTransactionManagementConfiguration source as shown below:

    public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
        // The main thing is this bean
    	@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
    	public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(a) {
    		BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
             // The source of transaction-related attributes is maintained internally
             // An interceptor is maintained internally for transaction execution, which is then relied on to start, commit, and roll back transactions
             // When a method that owns the transaction is called, the invoke method inside the interceptor is finally called
    		if (this.enableTx ! =null) {
    		return advisor;
    	public TransactionAttributeSource transactionAttributeSource(a) {
    		return new AnnotationTransactionAttributeSource();
    	public TransactionInterceptor transactionInterceptor(a) {
    		TransactionInterceptor interceptor = new TransactionInterceptor();
    		if (this.txManager ! =null) {
    		returninterceptor; }}Copy the code

    By convention, we take a look at the bean: BeanFactoryTransactionAttributeSourceAdvisor information.

2.2.1 BeanFactoryTransactionAttributeSourceAdvisor role

  • As usual, let’s look at its class inheritance diagram:

    As you can see, it belongs to the Advisor type. At this point, let’s recall that Spring AOP has a Advisor lookup process when querying aspects, pointcuts, and advice. If you don’t remember it well, let’s do it again. Continue with the images used in the previous article:

    One section of the code that looks for the logic that implements the Advisor interface looks like this:

    / / method coordinates: org. Springframework. Aop) framework. Autoproxy. BeanFactoryAdvisorRetrievalHelper# findAdvisorBeans
    public List<Advisor> findAdvisorBeans(a) {
        String[] advisorNames = this.cachedAdvisorBeanNames;
        if (advisorNames == null) {
            // Find the beans of type Advisor in the Spring container
            advisorNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
                this.beanFactory, Advisor.class, true.false);
            this.cachedAdvisorBeanNames = advisorNames;
        if (advisorNames.length == 0) {
            return new ArrayList<>();
        / /... Omit the process logic of going through all the beans, looking for beans with @AspectJ annotations, and parsing the beans.
    Copy the code
  • Remember this method? The idea is to find all of our sections and parse them into individual Advisors. And in the process of looking for affairs section, not iterate through all the beans, because our @ EnableTransactionManagement annotations have to import an Advisor in the spring container. Therefore, the transaction performance is better for the process of finding the transaction aspect. Because it leaves out the iterate through all the process of bean, when using the @ EnableTransactionManagement annotation automatically for us to import a type as the Advisor of the bean.

2.2.2 summarizes

  • The role of ProxyTransactionManagementConfiguration below can be used to summarize:

2.3 summarize

  • To sum up, our @ EnableTransactionManagement annotations in the underlying do is very clear, with a picture:

Third, the underlying execution principle of the transaction

  • This section is not intended to be further analyzed, as the steps and principles are in the Spring AOP Principles section: I’ll use my prehistorical powers to help you thoroughly understand the aop annotation @enableAspectJAutoProxy principle, which is analyzed in the chain of responsibility design pattern, although the actual operation on the link may be different. In AOP, the function of a chain on a link is to invoke the various advice we define. In the transaction call link, there is only one chain, is defined within the ProxyTransactionManagementConfiguration transactionInterceptor, in this link will be based on the current methods of transaction isolation mechanism to do some extra processing, However, the main process is to start the transaction, commit/roll back the transaction. If you want to understand its internal call details, you can refer to this method: org. Springframework. Transaction. The interceptor. TransactionInterceptor# invoke


  • The underlying principles of Spring transactions are relatively simple, much the same as Spring AOP. The only thing to note is Spring’s transaction isolation level and transaction propagation mechanism, which must be related to the transactionInterceptor mentioned above. If you want to learn more about its execution principle, can be looked into this method: org. Springframework. Transaction. The interceptor. TransactionInterceptor# invoke (all calls method with transaction features will all come to here).
  • Feel free to like, bookmark and follow my posts if you find them useful. :laughing:
  • I’m a slow walker, but I never walk backwards