Repository navigation
PlayIntegration
Grapht can provide dependency injection for Play 2 projects. Here's how.
Note: Grapht 0.11 introduces lifecycle management to shut down closable components when an injector shuts down. The provided Play integration does not yet support lifecycle-managed components. It also does not work with Play 2.4.
Our goal is to have Grapht provide our controller objects, rather than having static contoller methods. Then, it becomes much easier to isolate functionality all the way down the stack for automated testing.
The main trick here is to change the routes file to add @ symbols to controllers we wish to be instantiated. Then, remove the static declarations from handler methods.
An example of a line in routes:
GET /api/foo @controllers.FancyHandlers.foo()
Then, FancyHandlers looks like this:
public class FancyHandlers extends Controller {
private final FooDependency fooDependency;
@Inject
public FancyHandlers(FooDependency fooDependency) {
this.fooDependency = fooDependency;
}
public Result foo() {
this.fooDependency.blarg();
return ok("foo!");
}
}Our next goal is to actually inject FancyHandlers with FooDependency when it's instantiated. Create a class that extends GlobalSettings, and tell play about it in application.conf
In application.conf:
application.global=my.package.name.GlobalThe class:
public class Global extends GlobalSettings {
private static final Injector INJECTOR = createInjector();
/**
* Use grapht to return a controller instance.
*/
@Override
public <A> A getControllerInstance(Class<A> controllerClass) throws Exception {
return INJECTOR.getInstance(controllerClass);
}
/**
* Configure grapht dependencies here.
*/
private static Injector createInjector() {
InjectorBuilder builder = new InjectorBuilder();
// configure grapht here
builder.bind(FooDependency.class).to(FancyFooDependency.class);
return builder.build();
}
}Done. Play will now use grapht to provide controllers and their dependencies (all the way down the stack). Happy Playing!