假设我有一个如下课程:

public class ComplicatedImpl implements Complicated {
    @Inject
    public ComplicatedImpl(Integer normal, @Assisted String assisted);

    public void addListener(Listener listener);
}


现在,我有一个ComplicatedFactory像这样:

public interface ComplicatedFactory {
    public Complicated build(String assisted);
}


在使用FactoryModuleBuilder时是否可以绑定ComplicatedFactory以便在调用build()时执行与

ComplicatedImpl impl = new ComplicatedImpl(normal, assisted);
impl.addListener(listener);
return impl;


与直接返回新的ComplicatedImpl的正常情况相反?

我一直在尝试将ComplicatedImpl绑定到某种形式的Provider,但似乎我会绕圈绕圈...

最佳答案

我认为这在Guice中是不可能的;除了将显式构造函数参数与依赖项混合在一起,FactoryModuleBuilder几乎无能为力。幸运的是,编写手动工厂相对容易:

public class ListeningComplicatedFactory {
  @Inject Provider<Integer> normalProvider;

  public Complicated createComplicated(String assisted, Listener listener) {
    ComplicatedImpl impl = new ComplicatedImpl(normalProvider.get(), assisted);

    // If ComplicatedImpl uses member injection, inject an Injector and call
    // injector.injectMembers(impl) to call @Inject-annotated methods/fields.

    impl.addListener(listener);
    return impl;
  }
}


如果愿意将addListener放在Complicated接口上,则还可以选择编写一个包装器,该包装器注入ComplicatedFactory,创建新实例,并立即在它们上调用addListener。如果将ComplicatedFactory绑定在PrivateModule中,然后仅公开新的ComplicatedWrapperFactory,则这可能特别有效,从而使ComplicatedWrapperFactory成为创建新的Complicated实现的唯一方法。

07-27 13:50