结合 AspectJ 使用 @Transactional

你也可以通过 AspectJ 切面,在 Spring 容器外部使用 Spring 框架的 @Transactional 支持。 为此,首先使用 @Transactional 注解标注你的类(以及可选地标注你的类的方法), 然后将你的应用程序与 spring-aspects.jar 文件中定义的 org.springframework.transaction.aspectj.AnnotationTransactionAspect 进行链接(织入)。你还必须使用事务管理器来配置该切面。你可以使用 Spring 框架的 IoC 容器来负责依赖注入该切面。 配置事务管理切面最简单的方法是使用 <tx:annotation-driven/> 元素并将 mode 属性指定为 aspectj, 如 使用 @Transactional 中所述。 由于我们这里关注的是在 Spring 容器外部运行的应用程序,因此我们向你展示如何以编程方式实现。

在继续之前,你可能需要分别阅读 使用 @TransactionalAOP

以下示例展示了如何创建事务管理器并配置 AnnotationTransactionAspect 来使用它:

  • Java

  • Kotlin

// construct an appropriate transaction manager
DataSourceTransactionManager txManager = new DataSourceTransactionManager(getDataSource());

// configure the AnnotationTransactionAspect to use it; this must be done before executing any transactional methods
AnnotationTransactionAspect.aspectOf().setTransactionManager(txManager);
// construct an appropriate transaction manager
val txManager = DataSourceTransactionManager(getDataSource())

// configure the AnnotationTransactionAspect to use it; this must be done before executing any transactional methods
AnnotationTransactionAspect.aspectOf().transactionManager = txManager

当你使用此切面时,你必须标注实现类(或该类中的方法,或两者都标注),而不是该类实现的接口(如果有的话)。 AspectJ 遵循 Java 的规则,即接口上的注解不会被继承。

类上的 @Transactional 注解指定了该类中任何公共方法执行的默认事务语义。

类中方法上的 @Transactional 注解会覆盖类注解(如果存在)给出的默认事务语义。 你可以标注任何方法,无论其可见性如何。

要将你的应用程序与 AnnotationTransactionAspect 织入,你必须使用 AspectJ 构建你的应用程序 (请参阅 AspectJ 开发指南)或使用加载时织入。 有关使用 AspectJ 进行加载时织入的讨论,请参阅 Spring 框架中 AspectJ 的加载时织入