简体   繁体   中英

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).

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.

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