Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Guicing up the Play Framework: Dependency Injection with Guice and Play

DZone's Guide to

Guicing up the Play Framework: Dependency Injection with Guice and Play

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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.

  1. 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
    
  2. 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
    package services;
    
    public interface GreetingService {
        String greeting();
    }
    
      Followed up by its implementation here: app/services/RealGreetingService.java
    package services;
    
    public class RealGreetingService implements GreetingService {
        @Override
        public String greeting() {
            return "bonjour";
        }
    }
    
  3. 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. 
    package controllers;
    
    import com.google.inject.Inject;
    import play.mvc.Controller;
    import play.mvc.Result;
    import services.GreetingService;
    import views.html.index.*;
    
    public class Application extends Controller {
    
        @Inject
        private GreetingService greetingService;
    
        public Result index() {
            return ok(index.render(greetingService.greeting()));
        }
    }
    
  4. 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)
    
  5. 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.
    import com.google.inject.AbstractModule;
    import com.google.inject.Guice;
    import com.google.inject.Injector;
    import play.Application;
    import play.GlobalSettings;
    import services.GreetingService;
    import services.RealGreetingService;
    
    public class Global extends GlobalSettings {
    
        private Injector injector;
    
        @Override
        public void onStart(Application application) {
            injector = Guice.createInjector(new AbstractModule() {
                @Override
                protected void configure() {
                    bind(GreetingService.class).to(RealGreetingService.class);
                }
            });
        }
    
        @Override
        public <T> T getControllerInstance(Class<T> aClass) throws Exception {
            return injector.getInstance(aClass);
        }
    }
    
  6. If this has all worked, you should be able to run the application and see the message by visiting http://localhost:9000.
    $ play run
    
    Your greeting should appear like the screenshot below.
I've uploaded the sample application here.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}