Guice:协助注射和提供者

时间:2014-10-07 23:12:59

标签: java guice assisted-inject

假设我有一个课程如下:

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,但似乎我会绕着这个圈子四处走动......

1 个答案:

答案 0 :(得分:1)

我认为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立即。如果您在PrivateModule中绑定ComplicatedFactory然后只公开新的ComplicatedWrapperFactory,那么这可能会特别有效,这使得ComplicatedWrapperFactory成为创建新的复杂实现的唯一方法。