在 AspectJ 中使用 @Transactional

您也可以通过 AspectJ 切面在 Spring 容器外部使用 Spring Framework 的 @Transactional 支持。为此,首先使用 @Transactional 注解标记您的类(以及可选地标记您类中的方法),然后将您的应用程序与 spring-aspects.jar 文件中定义的 org.springframework.transaction.aspectj.AnnotationTransactionAspect 进行链接(织入)。您还必须使用事务管理器配置该切面。您可以使用 Spring Framework 的 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 注解指定了该类中任何 public 方法执行时的默认事务语义。

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

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