|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
将 @Transactional 与 AspectJ 结合使用
您还可以通过 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 开发指南),或者使用加载时织入。有关在 Spring 框架中使用 AspectJ 进行加载时织入的讨论,请参见Spring 框架中的 AspectJ 加载时织入。