Scala依赖注入简单模式

时间:2018-04-18 01:38:42

标签: scala dependency-injection

我希望你过得愉快!

根据框架的要求,我必须使用inject Configuration类并获取配置密钥。

问题是现在我必须重构我的代码,但我无法弄清楚我该怎么做。

问题

为了简单起见,我们考虑一个Sender类及其伴随对象。

class Sender(image: File, name: String) {

  def send() = { Sender.s3Client.send(image, name)  }

}

object Sender {

  val accessKey = config.get[String]("accessKey")
  val secretKey = config.get[String]("secretKey")

  val s3Client: AmazonS3 = ... withCredentials ( accessKey, secretKey) ...
}

这里我config.get方法应该是一个注入的对象。

问题

如何在此方案中注入Configuration类?

我不能像下面那样使用,因为其他一些方法用image和name param

实例化这个类
class Sender @Inject() (image: File, name: String, config: Configuration) { ... }

谢谢!

1 个答案:

答案 0 :(得分:2)

在Scala中,即使不使用DI Framework,也可以拥有自己的DI容器。

trait ConfigurationModule {

   def config: Configuration

}

trait S3Module {

   def accessKey: String
   def secretKey: String

   lazy val s3Client: AmazonS3 = ... withCredentials ( accessKey, secretKey) ...

}

object YourOwnApplicationContext extends ConfigurationModule with S3Module with ... {

  ...

  lazy config: Configuration = ConfigFactory.load()

  lazy val accessKey = config.get[String]("accessKey")
  lazy val secretKey = config.get[String]("secretKey")

}

现在所有的依赖项都在YourOwnApplicationContext

所以你可以这样做:

class Sender(image: File, name: String) {

  def send() = YourOwnApplicationContext.s3Client.send(image, name)

}

您可以阅读这些文章:

  1. MacWire
  2. Dependency Injection in Scala using MacWire
相关问题