Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice: inject dependency into @provides provider

I have a module in which I create a provider and that provider is needed as a dependency for another provider in the same module. However, this is not currently possible with my setup. How can I solve this issue? It should also be noted that all the dependencies are third party libraries and so I believe that I should not be binding this in my module (according to what Ive read).

Unfortunately, due to NDA I cannot provide the actual code, but an example of the dependency hierarchy can be seen below:

public MyModule extends AbstractModule {
    @Override
    protected void configure() {}

    @Singleton
    @Provides
    public Engine provideEngine(){
        Map<String, String> engineProperties = new HashMap<>();
        engineProperties.put("brand", "some brand");
        engineProperties.put("capacity", "2.6 litres");
        return new Engine(engineProperties);
    }

    @Inject
    @Provides
    public Car provideCar(Engine engine){
        Car car = new Car(engine);
        return car;
    }
}

Is short, I need to create a custom Engine, setting up some properties before hand and then use that Engine as a dependency for the Car creation (please note that i am fully aware that I cannot inject using the @Inject annotation in the module, however, I put this simply as a reference to what I want to achieve).

like image 220
aDiT Avatar asked Nov 08 '22 16:11

aDiT


1 Answers

Remove the @Inject annotation and you should be good to go. As listed in the @Provides Method User's Guide page:

If the @Provides method has a binding annotation like @PayPal or @Named("Checkout"), Guice binds the annotated type. Dependencies can be passed in as parameters to the method. The injector will exercise the bindings for each of these before invoking the method.

like image 161
Jeff Bowman Avatar answered Nov 15 '22 12:11

Jeff Bowman