Guice:将依赖项注入@provides 提供者

Guice: inject dependency into @provides provider

我有一个模块,我在其中创建了一个提供者,并且需要该提供者作为同一模块中另一个提供者的依赖项。但是,目前我的设置无法做到这一点。我该如何解决这个问题?还应该注意的是,所有依赖项都是第三方库,因此我认为我不应该在我的模块中绑定它(根据我读过的内容)。

很遗憾,由于 NDA,我无法提供实际代码,但可以在下面看到依赖层次结构的示例:

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;
    }
}

简而言之,我需要创建一个自定义引擎,事先设置一些属性,然后将该引擎用作创建汽车的依赖项(请注意,我完全知道我无法使用 @Inject 注入模块中的注释,但是,我将其简单地作为对我想要实现的目标的参考。

删除@Inject 注释,您就可以开始了。如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.