首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Scala中使用Spring @Transactional

在Scala中使用Spring @Transactional
EN

Stack Overflow用户
提问于 2010-12-08 17:30:09
回答 3查看 1.8K关注 0票数 4

我们有一个混合的Java和Scala项目,它使用Spring事务管理。我们使用Spring方面来编织带有@Transactional注解方法的文件。

问题是,Scala类并没有与Spring事务方面结合在一起。如何配置Spring来处理Scala中的事务?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-01-04 13:09:00

Spring需要您的事务边界从Spring管理的bean开始,因此这排除了@Transactional Scala类。

听起来简单的解决方案是创建服务外观,这些外观是实例化为Spring的@Transactional Java类。这些可以委托给你的Scala服务/核心代码。

票数 3
EN

Stack Overflow用户

发布于 2012-09-01 06:09:46

Scala特有的解决方案是使用Eberhard Wolff的闭包来创建手动事务。用法:

代码语言:javascript
复制
transactional() {
// do stuff in transaction
}

https://github.com/ewolff/scala-spring/blob/master/src/main/scala/de/adesso/scalaspring/tx/TransactionManagement.scala

https://github.com/ewolff/scala-spring/blob/master/src/main/scala/de/adesso/scalaspring/tx/TransactionAttributeWithRollbackRules.scala

点击此处:http://www.slideshare.net/ewolff/scala-and-spring (幻灯片41)

许可证: Apache

票数 2
EN

Stack Overflow用户

发布于 2015-02-08 19:43:56

在Scala中,Spring支持没有什么特别的,你可以不需要任何@Transactional代码就可以使用它。只需确保您拥有bean的“纯”特征,这些特征的实现将使用@Transactional注释。您还应该声明一个具有PlatformTransactionManager类型的bean (如果您使用的是基于.xml的Spring配置,则应该使用"transactionManager“作为bean名称,有关详细信息,请参阅EnableTransactionManagement's JavaDoc )。此外,如果您使用基于注释的配置类,请确保将这些类放置在它们自己的专用文件中,即不要在同一文件中放置任何其他类(伴生对象也可以)。下面是一个简单的工作示例:

SomeService.scala:

代码语言:javascript
复制
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:

代码语言:javascript
复制
@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!
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4385929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档