Spring事务的原理是基于AOP实现的,所以流程也可以理解为与AOP一样分为3步:解析切面、织入通知和运行时增强。
1、解析切面
Srping事务的是通过@EnableTransactionManagement注解开启的,该注解往IoC容器中注入了四个对象:InfrastructureAdvisorAutoProxyCreator(类似于AnnotationAwareAspectJAutoProxyCreator,用于创建代理类的)、BeanFactoryTransactionAttributeSourceAdvisor、TransactionAttributeSource、TransactionInterceptor。
其中InfrastructureAdvisorAutoProxyCreator实现了BeanPostProcessor的接口,因此会在第一个Bean实例化之前调用applyBeanPostProcessorsBeforeInstantiation方法,里面会跑到InfrastructureAdvisorAutoProxyCreator的postProcessBeforeInstantiation方法里面:
@Nullable
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;
}
然后会调用AbstractAutoProxyCreator的postProcessBeforeInstantiation方法对切面进行初始化,其流程和AOP初始化流程一致(这里要注意事务的切面是AnnotationAwareAspectJAutoProxyCreator调用findCandidateAdvisors跑到父类AbstractAdvisorAutoProxyCreator的findCandidateAdvisors方法里面调用BeanFactoryAdvisorRetrievalHelper的findAdvisorBeans方法加载BeanFactoryTransactionAttributeSourceAdvisor缓存起来的)被切面类顺便加载
public List<Advisor> fi