Playframework & Guice without routing

2020-07-28 08:26发布

问题:

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.