在 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 容器之外运行的应用程序,所以我们向您展示如何以编程方式实现它。
在继续之前,您可能需要阅读 使用 @Transactional 和 AOP。 |
以下示例展示了如何创建事务管理器并配置 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 Framework 中使用 AspectJ 的加载时编织。