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

Play-ing with Dependency Injection

DZone's Guide to

Play-ing with Dependency Injection

· Java Zone ·
Free Resource

Distribute microservices between the private and public clusters, yet maintain bi-directional connectivity. Content provided by IBM Developer.

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 thegreetingService 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 onhttps://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

Use this tool to look at the contents of GitHub and classify code based on the programming language used.  Content provided by IBM Developer.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}