注入数据库依赖项scala对象

时间:2017-04-16 07:39:30

标签: scala dependency-injection

有没有办法在Scala对象中注入Play数据库依赖?我知道我们可以为类

这样做
class MyClass @Inject() (db: Database) = {
}

但我想在没有实际使用Play插件的情况下注入依赖项。

我的build.sbt看起来像这样

scalaVersion := "2.11.8"

lazy val sparkVersion = "2.1.0"

lazy val hadoopVersion = "2.7.0"

lazy val jacksonVersion = "2.8.7"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % sparkVersion,
  "org.apache.spark" %% "spark-sql" % sparkVersion,
  "org.apache.hadoop" % "hadoop-common" % hadoopVersion,
  "com.databricks" %% "spark-csv" % "1.5.0",
  "org.codehaus.janino" % "janino" % "3.0.7",
  "com.databricks" % "spark-redshift_2.11" % "3.0.0-preview1",
  "com.amazonaws" % "aws-java-sdk-s3" % "1.11.34",
  "com.typesafe" % "config" % "1.3.1",
  "com.typesafe.play" % "play-json_2.11" % "2.4.6",
  "com.typesafe.play" %% "play" % "2.5.9",
  "com.typesafe.play" % "play-jdbc_2.11" % "2.5.14",
  "com.amazon.redshift" % "jdbc42" % "1.2.1.1001" from "https://s3.amazonaws.com/redshift-downloads/drivers/RedshiftJDBC42-1.2.1.1001.jar"
)

fork in Test := true

assemblyMergeStrategy in assembly := {
  case ".gitkeep" => MergeStrategy.discard
  case "META-INF/groovy-release-info.properties" => MergeStrategy.discard
  case "META-INF/MANIFEST.MF" => MergeStrategy.discard
  //case "log4j.properties" => MergeStrategy.deduplicate
  case x: String if x.matches( """META-INF/.*\.(SF|DSA|RSA)""") => MergeStrategy.discard
  case x: String if x.startsWith("META-INF/services/org.apache.lucene") => MergeStrategy.concat
  case x => MergeStrategy.first
}

我试过

object MyObject {
@Inject()
var db: Database = _
}

但它没有空指针异常

1 个答案:

答案 0 :(得分:4)

@Inject在这种情况下不起作用。 Object在语言级别上作为单身人士工作,而依赖注入是由配置驱动的,在Playframework的情况下,它是使用Guice引擎构建的。有效地DI仅适用于由DI创建或插入其中的对象,因此Guice至少应该知道MyObject的存在。

最佳选择是使用带@Inject注释的类

 case class MyObject @Inject() (db: Database)

如果不是这种情况,您可以从Application对象获取Injector引用( 已弃用 ,应避免使用)

object MyObject {
   lazy val db: Database = Play.unsafeApplication.injector.instanceOf[Database]
}