我有一些问题无法理解如何在 Play 2.4 中应用依赖注入(inject)的新功能。我熟悉 Guice,但在 Play 文档中没有解释实际绑定(bind)发生的方式和时间。我阅读了官方文档 [1] 并尝试使用最新的 Play Mailer [2] 作为示例。 Play Mailer 示例使用任意类并使用 @inject
注释 MailerClient
属性。当我尝试使用此类的对象时,属性为 null
,至少在调试时是这样。那么,我必须在何时何地进行实际注入(inject)?我对 @singleton
注释有同样的问题。它只是解释了如何注释它,而不是如何获取对象。我必须直接使用 Guice,还是以某种方式集成它?
[1] https://www.playframework.com/documentation/2.4.x/JavaDependencyInjection
最佳答案
我相信,绑定(bind)是通过 MailerModule 发生的添加到 play.modules.enabled . MailerModule为 MailerClient 提供 Guice 绑定(bind)。
play {
modules {
enabled += "play.api.libs.mailer.MailerModule"
}
要让 Guice 将 MailerClient 注入(inject)到您的对象中,应该通过 Guice 创建它。例如,如果您想在 Controller 中使用 @Inject MailerClient
或将服务注入(inject)到 Controller 中,则您的 Controller 需要通过 Guice 注入(inject)。 Recommended approach for this in Play 2.4正在将以下内容添加到您的 build.sbt:
routesGenerator := InjectedRoutesGenerator
关于java - 理解 Play 2.4 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31501996/