在 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
註解指定了該類中任何 public 方法執行時的預設事務語義。
類中方法上的 @Transactional
註解會覆蓋類註解(如果存在)提供的預設事務語義。您可以註解任何方法,無論其可見性如何。
要將您的應用程式與 AnnotationTransactionAspect
織入,您必須使用 AspectJ 構建您的應用程式(參見 AspectJ 開發指南)或使用載入時織入。有關 Spring Framework 中使用 AspectJ 進行載入時織入的討論,請參見Spring Framework 中的 AspectJ 載入時織入。