Spring cung cấp cơ chế xử lý giao dịch thông qua annotation @Transactional, kết hợp với mô hình AOP để bao bọc các phương thức cần quản lý giao dịch. Dưới đây là phân tích chi tiết về cách thức hoạt động của thành phần này.
Thành phần cốt lõi được cấu thành từ các lớp sau:
1. Phân tích annotation
Lớp SpringTransactionAnnotationParser thực hiện việc đọc thuộc tính từ annotation @Transactional và chuyển thành đối tượng TransactionAttribute. Ví dụ minh họa:
public TransactionAttribute extractTransactionConfig(AnnotatedElement targetElement) {
AnnotationAttributes configAttrs = AnnotationUtils.findMergedAnnotationAttributes(
targetElement, Transactional.class, false, false);
return (configAttrs != null) ? parseAttributes(configAttrs) : null;
}
2. Xác định điểm cắt (Pointcut)
Lớp TransactionAttributeSourcePointcut xác định phương thức cần được can thiệp dựa trên annotation. Phương thức matches kiểm tra xem phương thức có chứa annotation cần thiết hay không:
public boolean matches(Method method, Class<?> targetClass) {
TransactionAttributeSource source = getAttributeSource();
return (source != null && source.getTransactionAttribute(method, targetClass) != null);
}
3. Xử lý giao dịch
Trình chặn TransactionInterceptor thực hiện logic giao dịch. Khi phương thức được đánh dấu @Transactional được gọi, phương thức invoke sẽ được kích hoạt:
public Object proceedWithTransaction(MethodInvocation invocation) throws Throwable {
Class<?> targetClass = (invocation.getThis() != null) ?
AopUtils.getTargetClass(invocation.getThis()) : null;
return invokeInTransaction(invocation.getMethod(), targetClass, invocation::proceed);
}
4. Quản lý giao dịch
Lớp PlatformTransactionManager đóng vai trò trung tâm, định nghĩa các phương thức cơ bản:
public interface PlatformTransactionManager {
TransactionStatus beginTransaction(TransactionDefinition definition);
void commitTransaction(TransactionStatus status);
void rollbackTransaction(TransactionStatus status);
}
Các triển khai phổ biến bao gồm DataSourceTransactionManager và JpaTransactionManager. Spring tự động tìm kiếm implementation phù hợp thông qua tên bean hoặc annotation @Qualifier.
5. Định nghĩa giao dịch
Lớp TransactionDefinition chứa các thông số cấu hình giao dịch như mức độ cô lập (isolationLevel), thời gian chờ (timeout), và hành vi truyền dẫn (propagationBehavior). Ví dụ cấu hình:
@Transactional(
propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
timeout = 30
)
public void updateData() { ... }