Play-ing with Dependency Injection
December 8, 2014
Play
Guice
Dependency Injection
A few months ago I wrote about the lack of Dependency Injection in Play. As part of the 2.4 release of Play, Dependency Injection has been incorporated as part of the framework. JSR 330 is now implemented using Guice. This article will demonstrate how to use it. As a reference point, I will be using the same example as the one used in my previous article.
Note that this article uses a non final release of the Play Framework 2.4 (2.4.0-M2) so part of the framework may change before the final release.
Assuming you have the Play Framework already installed and you have created a sample application. If you require help, please refer to the instructions here.
1.Create a simple service that we will be injecting into our controller. First create an interface at the path app/services/GreetingService.java
package services;
public interface GreetingService {
String greeting();
}
Followed up by its implementation app/services/RealGreetingService.java.
package services;
public class RealGreetingService implements GreetingService {
@Override
public String greeting() {
return "bonjour";
}
}
2.Back in the GreetingService interface, add the @ImplementedBy Guice annotation to it.
@ImplementedBy(RealGreetingService.class)
public interface GreetingService {
public String greeting();
}
3.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.
public class Application extends Controller {
private final GreetingService greetingService;
@Inject
public Application(GreetingService greetingService) {
this.greetingService = greetingService;
}
public Result index() {
return ok(index.render(greetingService.greeting()));
}
}
4.Start the application and go to the website at http://localhost:9000. It should look like this.
I’ve upload the sample application here on https://github.com/codingricky/play-di-java. As you can see, it is much simplier now that DI has been incorporated directly into the framework.
###References### * Guicing up the Play Framework - Dependency Injection with Guice and Play * JSR 330 * Google Guice * Dependency injection with Play