我們有一個混合的Java和Scala項目,它使用Spring事務管理。我們使用Spring方面用@Transactional註釋方法編織文件。在Scala中使用Spring @Transactional
問題是,斯卡拉類沒有與Spring事務方面編織。我如何配置Spring將事務視爲Scala?
我們有一個混合的Java和Scala項目,它使用Spring事務管理。我們使用Spring方面用@Transactional註釋方法編織文件。在Scala中使用Spring @Transactional
問題是,斯卡拉類沒有與Spring事務方面編織。我如何配置Spring將事務視爲Scala?
Spring需要您的事務邊界以Spring管理的bean開始,因此這排除了@Transactional
Scala類。
這聽起來像是簡單的解決方案是使服務門面是@Transactional
Java類實例化爲Spring bean。這些可以委託給你的Scala服務/核心代碼。
Scala-only解決方案是使用Eberhard Wolff的閉包創建手動事務。用法:
transactional() {
// do stuff in transaction
}
這裏找到:http://www.slideshare.net/ewolff/scala-and-spring(臺41)
許可:Apache的
沒有什麼特別的春天在Scala和你@Transactional
支持可以使用它,而無需任何Java代碼。只要確保你具有bean的「純」特徵,這些實現將使用@Transactional
註釋。您還應該聲明一個類型爲PlatformTransactionManager
的bean(如果您使用的是基於.xml的Spring配置,則應使用「transactionManager」作爲bean名稱,詳情請參閱EnableTransactionManagement's JavaDoc)。另外,如果您使用的是基於註釋的配置類,請確保將這些類放置在它們自己的專用文件中,即不要在同一個文件中放置任何其他類(伴隨對象爲OK)。下面是簡單的工作例如:
SomeService.scala:
trait SomeService {
def someMethod()
}
// it is safe to place impl in the same file, but still avoid doing it
class SomeServiceImpl extends SomeService {
@Transactional
def someMethod() {
// method body will be executed in transactional context
}
}
AppConfiguration.scala:
@Configuration
@EnableTransactionManagement
class AppConfiguration {
@Bean
def transactionManager(): PlatformTransactionManager = {
// bean with PlatformTransactionManager type is required
}
@Bean
def someService(): SomeService = {
// someService bean will be proxied with transaction support
new SomeServiceImpl
}
}
// companion object is OK here
object AppConfiguration {
// maybe some helper methods
}
// but DO NOT place any other trait/class/object in this file, otherwise Spring will behave incorrectly!
一個簡單的解決方案(或解決方法)可以穿上Java接口的註解,讓您的Scala類實現這些接口。 – 2010-12-08 10:17:49