Skip to content
This repository was archived by the owner on Jan 3, 2024. It is now read-only.

PlayIntegration

Michael Ekstrand edited this page Jul 9, 2015 · 3 revisions

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.

Use controller instances, not static methods

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!");
    }
}

Extend GlobalSettings to build controllers with Grapht

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.Global

The 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!

Clone this wiki locally