依赖注入到Play Framework 2.5模块 [英] Dependency Injection to Play Framework 2.5 modules
问题描述
我有一个带有以下签名的模块类:
I have a module class with the following signature:
class SilhouetteModule extends AbstractModule with ScalaModule {
我想注入配置:
class SilhouetteModule @Inject() (configuration: Configuration) extends AbstractModule with ScalaModule {
但是它失败,并出现以下错误.
But it fails with the following error.
No valid constructors
Module [modules.SilhouetteModule] cannot be instantiated.
Play文档提到
在大多数情况下,如果在创建组件时需要访问配置",则应将配置"对象注入组件本身或...
In most cases, if you need to access Configuration when you create a component, you should inject the Configuration object into the component itself or...
,但我不知道如何成功完成.所以问题是,如何在Play 2.5中将依赖项注入模块类中?
, but I can't figure out how to do it successfully. So the question is, how do I inject a dependency into a module class in Play 2.5?
推荐答案
有两种解决方案可以解决您的问题.
There are two solutions to solve your problem.
第一个(以及更简单的一个):不要扩展 com.google.inject.AbstractModule
.而是使用 play.api.inject.Module
.扩展将强制您覆盖 def绑定(环境:环境,配置:配置):Seq [Binding [_]]
.在该方法中,您可以进行所有绑定,然后将配置作为方法参数插入.
First one (and the more straight forward one):
Do not extend the com.google.inject.AbstractModule
. Instead use the play.api.inject.Module
. Extending that forces you to override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]]
. Within that method you could do all your bindings and you get the configuration inserted as a method-parameter.
第二个(以及更灵活的一个):根据要注入的组件的需求,可以为要绑定的组件定义提供程序.在该提供程序中,您可以注入所需的任何内容.例如
Second one (and the more flexible one): Depending on your needs of the components you want to inject, you could define a provider for the component you want to bind. In that provider you could inject whatever you want. E.g.
import com.google.inject.Provider
class MyComponentProvider @Inject()(configuration:Configuration) extends Provider[MyComponent] {
override def get(): MyComponent = {
//do what ever you like to do with the configuration
// return an instance of MyComponent
}
}
然后,您可以在模块中绑定组件:
Then you could bind your component within your module:
class SilhouetteModule extends AbstractModule {
override def configure(): Unit = {
bind(classOf[MyComponent]).toProvider(classOf[MyComponentProvider])
}
}
第二个版本的优点是,您可以注入自己喜欢的任何内容.在第一个版本中,您只是"配置.
The advantage of the second version, is that you are able to inject what ever you like. In the first version you get "just" the configuration.
这篇关于依赖注入到Play Framework 2.5模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!