有没有办法在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 = _
}
但它没有空指针异常
答案 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]
}