简体   繁体   中英

How to get bound Instance with Generic via Application.injector() in play2.5

I cannot get access to a guice-bound instance in Play2 tests via the application interface.

Using Play2.5, assume an application using Guice for DI with a Guice module having:

@Singleton
@Provides
protected MyThing<String, Foo, Bar> createMyThing() {
}

In the junit Integration test using WithApplication I do this, using standard play2 classes:

public class ApplicationTest extends WithApplication {

    private Application playApp;

    @Override
    protected Application provideApplication() {
        playApp = new GuiceApplicationBuilder().build();
    }

    @Test
    public void testInject() {
        playApp.injector().instanceOf(new BindingKey<>(MyThing.class));
    }
}

This fails with

No implementation for MyThing was bound

Even though in the debugger, I see the Guice injector has a binding:

MyThing<String, Foo, Bar> -> instance

Now while there are solutions for Guice itself , I cannot seem to directly access those, and the Play DI abstraction does not seem to offer the ability to specify generics.

This hack seems to work to get the Guice Injector, by asking the play injector wrapper to return a bound Guice injector:

play.inject.Injector playInjector = playApp.injector();
com.google.inject.Injector guiceInjector = playInjector.instanceOf(com.google.inject.Injector.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM