在 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 的載入時編織。