【发布时间】:2016-02-26 15:10:50
【问题描述】:
如何在 Play 2.4 中创建一个 Actor 以便它使用 Guice 自动注入依赖项?我阅读了几篇他们使用 GuiceApplicationBuilder 然后创建演员的帖子。我不想控制播放应用程序的实例化方式。相反,我只想知道如何创建一个演员实例,以便使用 Guice 管理依赖项。
创建一个有 5 个工人的 RoundRobinRouter
class RouterActor extends Actor with ActorLogging {
val router = {
val routees = Vector.fill(5) {
val r = context.actorOf(Props[Worker])
context watch r
ActorRefRoutee(r)
}
Router(RoundRobinRoutingLogic(), routees)
}
def receive = {
case job: Job =>
router.route(job, sender())
}
}
扩展 AkkaGuiceSupport 并创建一个绑定 RouterActor 的模块
class RouterActorModule extends AbstractModule with AkkaGuiceSupport {
override def configure() = {
bindActor[RouterActor]("router-manager")
}
}
根据RouterModule中actor的名字使用guice DI注入RouterActor
class ScheduledReportGenerationService @Inject() (@Named("router-manager") serviceRouter: ActorRef) extends Actor {
def receive = {
case serviceInfo: ServiceContext => submitJobs(serviceInfo)
}
def submitJobs(serviceInfo: ServiceContext) = {
serviceRouter ? serviceInfo
}
}
如何初始化 ScheduledReportGenerationService Actor,以便 Guice 自动注入 RouterActor?我收到以下错误
java.lang.IllegalArgumentException: no matching constructor found on class vistoscheduler.ScheduledReportGenerationService for arguments []
我了解 system.actorOf 使用 Akka 创建 Actor,因此 Guice 无法注入依赖项。文档不是很清楚,我无法解决这个问题。
class SchedulerBootStrap extends Actor {
implicit val system = context.system
implicit val timeout = Timeout(5.minute)
def receive = {
case "BOOTSTRAP_SCHEDULER" => bootStrapServices()
}
def bootStrapServices() = {
lazy val scheduledReportGenerationService = system.actorOf(Props[ScheduledReportGenerationService], "scheduled-reports-service-actor")
scheduledReportGenerationService ? ServiceContext(1L)
}
}
【问题讨论】:
-
您是否在 conf 中启用了您的模块,例如
play.modules.enabled += "packagename.RouterActorModule"?
标签: playframework-2.0 akka guice