How does @Inject in Scala work
Asked Answered
O

1

12

I'm wondering how does @Inject annotation in Play-Scala works. It obviously injects a dependency, but I'm curious how is it working. When I was using it on class extending controller and set routes generator to injectroutesgenerator it seems to autmagically create objects from those classes, but how do I use it in other context?

I tried:

@Inject val mailer: MailerClient = null

But that doesn't seem to work. Are there any posibilities to @Inject things (that mailerClient, WS ets.) directly to a value, not to controller class?

Orthopedist answered 20/6, 2015 at 9:39 Comment(0)
B
8

Looks close. Change val to var because it is not final and needs to be injected at a latter stage.

@Inject var mailer: MailerClient = null

I'd check also that the MailerClient library is mentioned as a dependency in the project configuration. You could try with WSClient instead as it's included by default in the template:

@Inject var ws: WSClient = null

Especially as I know that this particular one works.

Update

Created a demo on GitHub which is the Play-Scala template with the index method changed as follows:

import play.api._
import play.api.libs.ws.WSClient
import play.api.mvc._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class Application extends Controller {

  @Inject var ws: WSClient = null

  def index = Action.async {
    ws.url("http://google.com").get.map(r => Ok(r.body))
  }

}
Brazier answered 20/6, 2015 at 23:45 Comment(6)
It seems legit but still nullPointerExceptionOrthopedist
When inject MailerClient into class it work as dream, but when i do it like that: "@Inject var mailer: MailerClient = null" github.com/Hajtosek/mailTest/blob/master/app/service/Mail.scalaOrthopedist
So you're telling me that i can ONLY use @Inject on Controllers?Orthopedist
You can use it in classes or traits, not objects but you can use the @Singleton annotation for a similar behaviour - docs.oracle.com/javaee/7/api/javax/inject/Singleton.htmlBrazier
So, this should theoretically work? github.com/Hajtosek/mailTest/blob/master/app/service/Mail.scalaOrthopedist
That's fine, you'll need to tell the system about the injectable module (@Singleton by itself isn't enough). Have a look at this for a Play 2.4 specific example: https://mcmap.net/q/1011424/-how-to-do-database-initialization-when-using-di-in-play-2-4 Have a look also at this for more Scala ways of doing it: https://mcmap.net/q/1011425/-is-it-possible-to-inject-an-object-with-scala-guiceBrazier

© 2022 - 2024 — McMap. All rights reserved.