Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does @Inject in Scala work

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?

like image 517
Haito Avatar asked Jun 20 '15 09:06

Haito


People also ask

How does @inject annotation work?

A method annotated with @Inject that overrides another method annotated with @Inject will only be injected once per injection request per instance. A method with no @Inject annotation that overrides a method annotated with @Inject will not be injected. Injection of members annotated with @Inject is required.

What does @inject annotation mean?

The @Inject annotation lets us define an injection point that is injected during bean instantiation.

What is @inject in constructor?

Constructor Injection is the most common form of Dependency Injection. Constructor Injection is the act of statically defining the list of required dependencies by specifying them as parameters to the class's constructor.


1 Answers

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

}
like image 179
bjfletcher Avatar answered Oct 13 '22 15:10

bjfletcher