对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-doc.cadn.net.cn

@Transactional与 AspectJ

您还可以使用 Spring 框架的@TransactionalSpring 外部的支持 container 通过 AspectJ 切面。为此,请先为您的类添加注释 (以及可选的类的方法)与@Transactional注解 ,然后将您的应用程序与org.springframework.transaction.aspectj.AnnotationTransactionAspectspring-aspects.jar文件。您还必须使用事务配置 aspect 经理。你可以使用 Spring 框架的 IoC 容器来处理 dependency-injecting 方面。配置事务的最简单方法 管理方面是使用<tx:annotation-driven/>元素并指定mode属性设置为aspectj@Transactional.因为 我们在这里重点介绍在 Spring 容器之外运行的应用程序,我们展示了 你如何以编程方式做到这一点。spring-doc.cadn.net.cn

在继续之前,您可能需要阅读@TransactionalAOP 分别。

以下示例显示了如何创建事务管理器并配置AnnotationTransactionAspect要使用它:spring-doc.cadn.net.cn

// 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
当您使用此方面时,您必须注释 implementation 类(或方法 在该类中或两者中),而不是该类实现的接口(如果有)。AspectJ 遵循 Java 的规则,即不继承接口上的 Comments。

@Transactional类上的 annotation 指定默认的事务语义 用于执行类中的任何公共方法。spring-doc.cadn.net.cn

@Transactional类中方法的注释将覆盖默认值 类注解(如果存在)给出的交易语义。您可以注释任何方法, 无论可见性如何。spring-doc.cadn.net.cn

要使用AnnotationTransactionAspect,您必须在 你的应用程序与 AspectJ 一起(参见 AspectJ 开发 Guide) 或使用加载时编织。有关使用 AspectJ 进行加载时编织的讨论,请参见 Spring Framework 中的 Load-time weaving with AspectJspring-doc.cadn.net.cn