Play Framework Dependency Injection

旧巷老猫 提交于 2019-12-06 02:36:18
Jon Burgin

I noticed you are using Java. Here is how I got it to work for injecting into a controller.

First, I created the following 4 classes :

MyController:

package controllers;

import play.mvc.*;
import javax.inject.Inject;

public class MyController extends Controller {

@Inject
private MyInterface myInterface;
    public Result someActionMethodThatUsesMyInterface(){
        return ok(myInterface.foo());
    }
}

MyInterface:

package models;

public interface MyInterface {
    String foo();
}

MyImplementation2Inject:

package models;

public class MyImplementation2Inject implements MyInterface {
    public String foo() { 
        return "Hi mom!";
    }
}

MyComponentModule:

package modules;

import com.google.inject.AbstractModule;
import models.MyInterface;
import models.MyImplementation2Inject;

public class ComponentModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(MyInterface.class).
                to(MyImplementation2Inject.class);
    }
}

Now the final part, that took me a silly long time to figure out, was to register the module. You do this by adding the following line to the end of the application.conf file, which is located in the conf directory:

play.modules.enabled += "modules.MyComponentModule"

I hope this was helpful to you. :)

BenjaminParker

I use cake pattern and my own version of Global overriding getControllerInstance

https://github.com/benjaminparker/play-inject

Cheers

Ben

Sorry, this is a late response, but here's our example

https://github.com/typesafehub/play-guice

Have you tried using some different approach to DI than Guice? We also tried implementing a project with Guice or Spring but ended in registering our dependencies in objects that implement trait such as:

trait Registry {
   def userDao: UserDao
...

}

object Registry {
  var current: Registry = _
}

object Environnment {
 object Dev extends Registry {
  val userDao = ...
//implement your environment for develpment here
}
 object Test extends Registry {
  val userDao = ...
//implement your ennviroment for tests here e.g. with mock objects
}
}

Another good approach wich might fit for you is the cake pattern (just google for it).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!