Play WS client within a module

254 Views Asked by At

I am trying to use the WS client with play 2.7.4 inside a module and I am running into issues. I would prefer to not create the client myself as described here but rather dependency inject it with guice. This doesn't seem to work, my instance is null. If I use the WS client outside the module, everything works.

According to what I read here only Config and Environment are available at that point from within the module, nothing else is bound yet.

Is there any way I can achieve this?


[edit 1]

What i understand from this answer is to create a provider class like this where I inject it normally

public class WSClientProvider implements Provider<WSClient> {

WSClient wsClient;

@Inject
public WSClientProvider(WSClient wsClient) {
    this.wsClient = wsClient;
}

@Override
public WSClient get() {
    return wsClient;
}

}

and then inside the module to just bind it like this

bind(WSClient.class).toProvider(WSClientProvider.class);

But this is not working in my case. What am I missing here?


[edit 2]

This is my module at the moment

public class SecurityModule extends AbstractModule {

private final Environment environment;
private final Config configuration;

public SecurityModule(final Environment environment, final Config configuration) {
    this.environment = environment;
    this.configuration = configuration;
}

@Override
protected void configure() {
    ...some bindings...
}

@Provides
private ObjectA provideMyObjectA() {
    return new ObjectA(); <-- we want to inject the WSClient inside this object

}
1

There are 1 best solutions below

1
On BEST ANSWER

I think you may need to take it a little further

public class ObjectAProvider implement Provider<ObjectA> {
     @Inject
     WSClient wsClient;

     public ObjectA get() {
          return new ObjectA(wsClient);
     }
}

Or you'd have to manually inject within the provider method:

ObjectA objectA = injector.getInstance(ObjectA.class);
return objectA;

Once you have the injector created.