前言
上一篇文章讲了Spring的Aop,这里讲一下Spring的事务管理,Spring的事务管理是建立在Aop的基础上的,相比Aop,事务管理的实现耦合性比较小,自定义就比较简单了。
自定义事务
Spring的开启事务管理主要是通过*@EnableTransactionManagement注解来实现的。 查看源码就会发现,这个注解主要是注入了两个类InfrastructureAdvisorAutoProxyCreator和BeanFactoryTransactionAttributeSourceAdvisor*,而且这两个类是通过其他的Configure类导入的。
- InfrastructureAdvisorAutoProxyCreator继承自AbstractAutoProxyCreator,自定义Aop里介绍过这个类,主要是读取Advisor类,并对符合的bean进行二次代理。
- BeanFactoryTransactionAttributeSourceAdvisor就是被扫描的Advisor类。这个类会扫面被Transactional注释的类的方法,并提供TransactionInterceptor,来代理被注释的方法。
完整的代码参考Github,这里介绍一下几个关键的类。
- 自定义的注解,简便起见注解的属性就不列出来了,跟Transactional的属性一样。
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyTransactional {
....
}