I would like to know if it's possible to inject dependencies using Guice without having to pass by the routing.
If it is how can I call my class Test @Inject()...
within my application ?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I think there are two ways to use Guice in Play framework:
1) Directly instantiate an object based on the binding:
Add Guice to your Build.scala app dependencies
val appDependencies = Seq(
"com.google.inject" % "guice" % "3.0"
)
Create a Global class, which extends GlobalSettings, and bind interface to implementation in configure():
public class Global extends GlobalSettings {
private Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(TestInferface.class).to(TestImpl.class);
}
});
}
In your Controller or any other class, use the @Inject annotation to get an instance of the interface:
@Inject
private Test test;
2) Dependency Injection for Play Controller
Override GlobalSettings.getControllerInstance to manage controller class instantiation either via Guice:
@Override
public <A> A getControllerInstance(Class<A> controllerClass) throws Exception {
return injector.getInstance(controllerClass);
}
How to use the Guice injection?
GET /test1 @controllers.ApplicationTest1.index()
GET /test2 @controllers.ApplicationTest2.index()
Route definitions starting with @ will be managed by play.GlobalSettings#getControllerInstance method.