Technology Sharing

Spring tx @Transactional detailed explanation of `Advisor`, `Target`, `ProxyFactory

2024-07-11

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

In Spring,@TransactionalThe processing of annotations involves several key components, includingAdvisorTargetProxyFactoryEtc. Below is a detailed analysis and code examples explaining how these components work together.

1. Introduction to key components

1.1 Advisor

AdvisorIt is a Spring AOP concept, which includes pointcut and advice.TransactionAttributeSourceAdvisorIs a typical Advisor.

1.2 Target

TargetRefers to the target object being proxied, that is, the object that actually executes the business logic.

1.3 ProxyFactory

ProxyFactoryIt is a factory class provided by Spring for creating proxy objects. It can create proxy objects using JDK dynamic proxy or CGLIB.

2. @Transactional processing flow

  1. Parsing Annotations: Spring Scan@Transactionalannotation.
  2. Create Advisor: Create a transaction processing logicAdvisor
  3. Creating a proxy object:useProxyFactoryCreate a proxy object for the target object andAdvisorAdded to the proxy object.

3. Code Examples

3.1 Configuration Class

First, through@EnableTransactionManagementEnable transaction management.

import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class AppConfig {
    // DataSource, EntityManagerFactory, TransactionManager beans configuration
}