在Scala中使用Guice和MacWire的步驟如下:
libraryDependencies += "com.google.inject" % "guice" % "4.2.3"
libraryDependencies += "com.softwaremill.macwire" %% "macros" % "2.3.7"
libraryDependencies += "com.softwaremill.macwire" %% "macros" % "2.3.7" % "provided"
import com.google.inject.AbstractModule
class MyModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[MyService]).to(classOf[MyServiceImpl])
}
}
import com.softwaremill.macwire._
class MyClass(myService: MyService) {
// ...
}
val injector = new MyModule()
val myClass = wire[MyClass]
通過以上步驟,您就可以在Scala中使用Guice和MacWire來管理依賴注入。Guice用于創建依賴注入容器并注冊依賴關系,而MacWire則用于方便地注入依賴。