6
votes

I have issues to understand how to apply the new feature of Dependency Injection in Play 2.4. I'm familiar with Guice and miss in the Play Documentation an explanation how and when the actual binding is happening. I read the official docu [1] and tried to use the latest Play Mailer [2] as an example. The Play Mailer example uses an arbitrary class and annotates the MailerClient property with @inject. When I try to use an object of this class the property is null, at least while debugging. So, where and when do I have to do the actual injection? I have the same issue for the @singleton annotation. It is just explained how to annotate it, but not how to get an object. Do I have to use Guice directly, or is it integrated some how?

[1] https://www.playframework.com/documentation/2.4.x/JavaDependencyInjection

[2] https://github.com/playframework/play-mailer

1
Can you show us your code? - Salem
Its basically like the official Play Mailer Example. I initiate the MyComponent in another class and call the sendMail() method. - linsenfips
I'm also confused by this and would love to see some more examples out there. I'm writing some S3 code and I have an S3File object dependent on an S3Service which should be injected. How do I create a new instance of S3File with S3Service injected into it? Do I create an Injector in my controller? In that case I guess I would use 'injector.getInstance(S3File.class)' instead of 'new S3File'? How do I create the injector - it seems like overkill to have to create a specific impl of AbstractModule to do the binding for this one class. What does the @ImplementedBy on my interface do if not this? - eljaydub

1 Answers

1
votes

I believe, the binding is happening through MailerModule added to play.modules.enabled. MailerModule provides the Guice binding for MailerClient.

play {
  modules {
    enabled += "play.api.libs.mailer.MailerModule"
  }

For Guice to inject MailerClient into your object, it should be created through Guice. For example, if you would like to use @Inject MailerClient in a Controller or a Service injected into controller, your controller needs to be injected through Guice. Recommended approach for this in Play 2.4 is adding the following to your build.sbt:

routesGenerator := InjectedRoutesGenerator