GuiceApplicationLoader配置错误

时间:2015-07-01 07:58:15

标签: playframework playframework-2.4

所以,我正在尝试用类似这样的东西来实现编译时DI:

package modules

class MyModule extends AbstractModule {
  def configure() {
    bind(classOf[MyT]).to(classOf[MyTImpl])
  }
}

class MyApplicationLoader extends GuiceApplicationLoader {
  override protected def builder(context: ApplicationLoader.Context): GuiceApplicationBuilder = {
  initialBuilder
    .in(context.environment)
    .loadConfig(context.initialConfiguration)
    .overrides(overrides(context): _*)
    .load(new MyModule)
  }
}

application.conf包含一行:

play.application.loader = "modules.MyApplicationLoader"

但是,当我尝试启动应用程序时,出现错误:

ConfigurationException: Guice configuration errors:

1) No implementation for play.api.Application was bound.
  while locating play.api.Application

1 error

No source available, here is the exception stack trace:
->com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for play.api.Application was bound.
  while locating play.api.Application

1 error
     com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1042)
     com.google.inject.internal.InjectorImpl.getProvider(InjectorImpl.java:1001)
     com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1051)
....

不明白为什么这不起作用,因为我见过的所有例子都没有涉及更多内容。我在俯瞰什么?

2 个答案:

答案 0 :(得分:3)

使用bindings代替load

class MyApplicationLoader extends GuiceApplicationLoader {
  override protected def builder(context: ApplicationLoader.Context): GuiceApplicationBuilder = {
  initialBuilder
    .in(context.environment)
    .loadConfig(context.initialConfiguration)
    .overrides(overrides(context): _*)
    .bindings(new MyModule)
  }
}

答案 1 :(得分:1)

我不确定你要在这里实现什么,但这不是编译时依赖注入的工作原理。 Guice在运行时发挥其魔力。但是,如果您希望在应用程序启动后立即准备好依赖项,请使用预先加载。 Guice已经提供了所需的所有工具:

MyModule的

class MyModule extends AbstractModule {
  def configure() {
    bind(classOf[MyT]).to(classOf[MyTImpl]).asEagerSingleton()
  }
}

application.conf

play.modules.enabled += "modules.MyModule"

因为MyTImpl将作为单例加载,所以它必须没有实例绑定数据。考虑scala术语中的object。始终会注入完全相同的MyTImpl实例。