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?

Haito
  • 2,039
  • 1
  • 24
  • 35

1 Answers1

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))
  }

}
bjfletcher
  • 11,168
  • 4
  • 52
  • 67
  • It seems legit but still nullPointerException – Haito Jun 21 '15 at 14:12
  • When inject MailerClient into class it work as dream, but when i do it like that: "@Inject var mailer: MailerClient = null" https://github.com/Hajtosek/mailTest/blob/master/app/service/Mail.scala – Haito Jun 21 '15 at 14:21
  • So you're telling me that i can ONLY use @Inject on Controllers? – Haito Jun 21 '15 at 14:37
  • You can use it in classes or traits, not objects but you can use the @Singleton annotation for a similar behaviour - https://docs.oracle.com/javaee/7/api/javax/inject/Singleton.html – bjfletcher Jun 21 '15 at 14:47
  • 1
    Thank you very much! You helped me a lot. – Haito Jun 21 '15 at 15:18
  • So, this should theoretically work? https://github.com/Hajtosek/mailTest/blob/master/app/service/Mail.scala – Haito Jun 21 '15 at 17:56
  • 2
    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: http://stackoverflow.com/a/30959808/722180 Have a look also at this for more Scala ways of doing it: http://stackoverflow.com/a/24823300/722180 – bjfletcher Jun 21 '15 at 18:39