One of the features lacking out of the box for Play is Dependency Injection. Coming from a background of JEE, this seemed to be quite a significant omission.
Fortunately, it is not very difficult to set it up. This article will take you through the steps of adding Guice to your Play application.
The first step is to add the Guice dependency to your build.sbt file or Build.scala (if you’re using Play 2.1.X or lower). Your build.sbt should look like this:
name := “sample-play-with-guice”
version := “1.0-SNAPSHOT”
libraryDependencies ++= Seq(
javaJdbc,
javaEbean,
cache,
“com.google.inject” % “guice” % “4.0-beta”
)
play.Project.playJavaSettings
Now let’s create a simple service that we will be injecting into our controller. First create an interface at the path app/services/GreetingService.java.
Followed up by its implementation here: app/services/RealGreetingService.java
package services;
public class RealGreetingService implements GreetingService {
@Override
public String greeting() {
return “bonjour”;
}
}
Now let’s go to the Application controller and inject the GreetingService into it. The key things here are the instance variable with the @Inject annotation and the controller index method not being static anymore, as it needs access to the greetingService instance variable.
Go to your routes file and put an @ in front of the index route to indicate that it is no longer static.
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / @controllers.Application.index()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path=”/public”, file)
Lastly, create a Global.java class at app/Global.java. Create an injector and override the getControllerInstance method to return instances from the injector. When a route has a prefix of @, Play will call this method.
We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.Ok