如何用spring scala去耦?

时间:2015-01-26 21:55:04

标签: spring scala

我喜欢将Spring添加到我的Scala项目中用于教育目的。但我不明白Spring Scala解耦组件的优势。

我创建了一个简单的配置:

import org.springframework.scala.context.function.FunctionalConfiguration

class Configuration extends FunctionalConfiguration {
  bean() {
    new Service()
  }
}

和简单的服务:

class Service {
  def method = "Bonjour tout le monde!"
}

然后是同时使用两者的应用程序:

import org.springframework.scala.context.function.FunctionalConfigApplicationContext

object Application extends App {
    implicit val context = FunctionalConfigApplicationContext(classOf[Configuration])

    val service = context.getBean(classOf[Service])
    println(service.method)
}

这只是我对Spring Scala示例的解释和实现。

我的应用程序仍然了解Service类。我可以写:

val service = new Service() // instead of asking for a Bean which has classname Service
println(service.method)

具有相同的效果。

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

这会将Service与实例化的使用分开。例如。如果将来Service更改依赖于其他InnerService,或者由于某种原因而在构造函数中无法完成某些初始化,但需要在使用之前在方法调用中进行({ {1}}或某些此类内容,或者如果您想用模拟的.connectToDatabase()替换Service进行测试,那么您可以在不更改这两行代码的情况下执行此操作:

val service = context.getBean(classOf[Service])
println(service.method)

如果编程到接口而不是实现,例如

trait IService {
  def method: String
}
class Service extends IService...

val service = context.getBean(classOf[IService])

然后你也可以轻松地将Service替换为不同的实现,但是考虑到额外的代码行,我可能不会这么做,直到我实际上有多个实现。

我不确定Spring是否有自己的权重(它是一个非常大而复杂的库),特别是在Scala中,它具有更简洁的构造函数语法。但无论您是否使用Spring,都值得将依赖关系的构造与应用程序的“连接”与实际使用区分开来。 IMO使用Foo的类Service应该通过其构造函数class Foo(service: Service)显式接受它,并将Service的构造/初始化保留给专用于的类/或函数这一点。